版权声明:欢迎提问:[email protected] https://blog.csdn.net/include_heqile/article/details/81945645
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/description/
我的解决方案:
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public static ListNode deleteDuplicates(ListNode head) {
//处理空链表和单元素链表
if(head==null||head.next==null) return head;
boolean first = true;
ListNode res = null;
ListNode result = null;
int tmp;
for(;head.next!=null;) {
//这个while循环会找到一个不重复的节点
while(head.next==null&&head.val==head.next.val) {
tmp=head.val;
while(head!=null&&head.val==tmp)
head=head.next;
if(head==null) {
if(res!=null)
//在结果最后加上空节点
res.next=head;
return result;
}
}
if(first){
res = head;
//因为res需要发生变化,所以让result作为最终返回结果
result=res;
first=false;
}
else {
res.next=head;
res=res.next;
}
head=head.next;
if(head==null) break;
}
return result;
}
public static void main(String[] args) {
ListNode head= new ListNode(1);
head.next=new ListNode(2);
head.next.next=new ListNode(3);
head.next.next.next=new ListNode(3);
head.next.next.next.next=new ListNode(4);
head.next.next.next.next.next=new ListNode(4);
head.next.next.next.next.next.next=new ListNode(5);
deleteDuplicates(head);
}
}