https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/
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) { ListNode new_head = head; while(head != null && head.next != null){ if(head.val == head.next.val){ if(head.next.next != null){ head.next = head.next.next; }else{ head.next = null; } } if(head.next != null && head.val != head.next.val){ head = head.next; } } return new_head; } }
解题思路:
如果后面节点的value和当前节点一样,就把head.next置为下下个节点。如果value和当前节点不同,就看后面一个节点,如此往复。但需要一个引用,永远指向head,以作返回。
上面代码有冗余,下面代码为同样思想。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null) { return null; } ListNode cur = head; while (cur.next != null) { if (cur.next.val == cur.val) { cur.next = cur.next.next; } else { cur = cur.next; } } return head; } }
2015/03/03更新了一个清楚点的code
注意这里的思想是,traverseNode的值与前一个值比较,比前面的节点大就加入,否则往后一个继续看。想想为什么不能与后面的比较?
/** * 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) { if(head == null){ return head; } ListNode traverseNode = head.next; ListNode keepNode = head; int preVal = head.val; while(traverseNode != null){ if(traverseNode.val > preVal){ preVal = traverseNode.val; keepNode.next = traverseNode; keepNode = keepNode.next; } traverseNode = traverseNode.next; } //这一步不能忘,要删除结尾所有的相同的值,比如1-1 keepNode.next = null; return head; } }
update 2015/05/19:
二刷
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null) { return head; } ListNode cur = head; ListNode slow = head; while(cur != null) { if(cur.next != null && cur.next.val == cur.val) { cur = cur.next; } else { slow.next = cur.next; cur = cur.next; slow = slow.next; } } return head; } }