删除链表中重复的节点,但是重复的节点得留一个
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; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { if(head==null||head.next==null) return head; 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.next=cu;//删除重复节点 }else{ node=node.next; } } return head; } }