Deleting duplicates a linked lists Java -
i trying implement method deletes duplicates linked list. i've managed take care of tail. in other words, if tail's data
duplicate, program wouldn't throw exception error
. now, i'm trying take care of head such if head
's data duplicate, want set head
= head.next
duplicate no longer in linked list. method deleteduplicates
not handle head
. have suggestions fix problem?
class node { private node next = null; private int data; public node(int d) { data = d; } void appendtotail(int d) { node end = new node(d); node n = this; while(n.next != null) { n = n.next; } n.next = end; } void print() { node n = this; while(n != null) { system.out.println(n.data); n = n.next; } } node deleteduplicates(node head, int d) { node n = head; if(n.data == d) { head = head.next; n = n.next; } while(n != null) { if(n.next.data == d) { if(n.next == null && n.next.data == d) { return head; } n.next = n.next.next; } n = n.next; } return head; } public static void main(string [] args) { node x = new node(9); x.appendtotail(5); x.appendtotail(9); x.appendtotail(6); x.appendtotail(9); x.appendtotail(7); x.appendtotail(9); x.appendtotail(8); x.appendtotail(9); x.deleteduplicates(x, 9); x.print(); } }
the problem in code haven't reassigned head after deletion. if modify follows, think head deletion problem solved.
x = x.deleteduplicates(x, 9);
needless say, there other efficient methods hashing can used bring down time complexity of code.
Comments
Post a Comment