Created
March 1, 2013 02:48
-
-
Save daifu/5062122 to your computer and use it in GitHub Desktop.
Given a sorted linked list, delete all duplicates such that each element appear only once.
This file contains hidden or 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
| /** | |
| * Given a sorted linked list, delete all duplicates such that each element appear only once. | |
| For example, | |
| Given 1->1->2, return 1->2. | |
| Given 1->1->2->3->3, return 1->2->3. | |
| * Definition for singly-linked list. | |
| * public class ListNode { | |
| * int val; | |
| * ListNode next; | |
| * ListNode(int x) { | |
| * val = x; | |
| * next = null; | |
| * } | |
| * } | |
| */ | |
| public class Solution { | |
| public ListNode deleteDuplicates(ListNode head) { | |
| // Start typing your Java solution below | |
| // DO NOT write main() function | |
| if (head == null) return null; | |
| ListNode cur = head; | |
| ListNode ahead; | |
| while(cur.next != null) { | |
| ahead = cur.next; | |
| if(ahead.val == cur.val) { | |
| ahead = ahead.next; | |
| cur.next = ahead; | |
| } else { | |
| cur = ahead; | |
| } | |
| } | |
| return head; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment