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
.
删除链表中所有重复的节点。
Remove Duplicates from Sorted List 是删除链表重复节点,但是要留下一个重复的节点。
这题因为第一个节点也可能重复,所以需要另外新建一个节点,指向该链表。
遍历链表,当下一个节点和当前节点不同,将当前节点加到链表中(将链表的next指向该节点)。当下一个节点和当前节点相等,则继续遍历,直到不相等的那一个,然后继续判断这个不相等的节点的下一个节点和该节点相不相等。见下面代码。
/** * 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||head.next==null) return head; ListNode dummy=new ListNode(0); dummy.next=head; ListNode p=dummy;//用于存结果 ListNode node=head; //用于遍历 while(node!=null&&node.next!=null){ if(node.next.val==node.val){ ListNode cu=node.next; while(cu!=null&&cu.val==node.val) cu=cu.next; node=cu;//将节点移到下一个不相等的节点,跳过这些相等的,然后继续进行下一轮判断。 continue; }else{ p.next=node; p=p.next; node=node.next; } } p.next=node; return dummy.next; } }