Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
解题思路 :
建立 fake noed 加在head 前面。cur = head; 比较cur 和 cur.next的值, 如果相等,记录下该值,并且从pre.next开始遍历到不等于 val的那个值,将中间的node 删除。
/** * 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 safe=new ListNode(0); safe.next=head; // 记录重复节点的值 int val=0; ListNode pre=safe;ListNode cur=head; while(cur!=null&&cur.next!=null){ ListNode n = cur.next; if(n.val == cur.val){ val=cur.val; // 从pre.next 开始遍历,如果pre.next 不为null 且值等于val,删除该节点 while(pre.next!=null&&pre.next.val==val){ pre.next=pre.next.next; } cur=pre.next; }else{ pre=cur; cur=cur.next; } } return safe.next; } }