-
-
Save InterviewBytes/247c758ee508a9d6bfa871c7fcc9dc5b to your computer and use it in GitHub Desktop.
Remove duplicates from a linked list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.linkedlists; | |
public class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { | |
val = x; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interviewbytes.linkedlists; | |
public class RemoveDuplicates { | |
public ListNode deleteDuplicates(ListNode head) { | |
if (head == null) return null; | |
ListNode current = head; | |
ListNode sentinel = new ListNode(0); | |
sentinel.next = current; | |
head = head.next; | |
while (head != null) { | |
if (head.val != current.val) { | |
current.next = head; | |
current = current.next; | |
} | |
head = head.next; | |
} | |
current.next = null; | |
return sentinel.next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment