java - Generic Doubly Linked List Implementation -
so have basic generic implantation of generic doubly linked list. have created insert method going add node according order.
public class doublyll <t extends comparable<t>> { dnode<t> head; dnode<t> tail; public void insertinorder(t item) { //to create "ordered" linked list dnode <t> n = new dnode<>(); if (head == null) { head = n; n.data = item; } else { dnode<t> temp = head; while (temp != null && n.data.compareto(temp.data) > 0) { // line 18 temp = temp.next; } if (temp == head) { //inserting node in first head.prev = n; n.next = head; head = n; n.data = item; } else if (temp == null) { // inserting @ last tail.next = n; n.prev = tail; tail = n; n.data = item; } else { //inserting in middle n.prev = temp.prev; n.next = temp; temp.prev.next = n; temp.prev = n; n.data = item; } } } @override public string tostring() { dnode temp = head; string str = ""; while (temp != null) { str += temp.data + " "; temp = temp.next; } return str; } public static void main(string[] args) { doublyll<integer> list = new doublyll<>(); list.insertinorder(2); list.insertinorder(222); //line 62 list.insertinorder(22222); system.out.println(list); } } class dnode<t> { t data; dnode prev; dnode next; } however, when i'm running i'm getting nullpointerexception @ line 18 , 62. can rid of make ordered list like, "2, 22, 2222?
it's hard what's problem without stack trace looks instead of
if (head == null) { head = n; n.data = item; } you should have
if (head == null) { head = n; tail = n; n.data = item; } otherwise tail remains null.
Comments
Post a Comment