1 解题思想
首先,这道题和之前的问题都挺像的,只是变成了链表,所以可以参照:
Leetcode 80. Remove Duplicates from Sorted Array II 重复移除 解题报告这里写链接内容
使用链表的话,也就是需要记得保存一下上一个的值的状态,决定是否需要将其移除(或者添加到不重复的链表上)
2 原题
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.
Subscribe to see which companies asked this question
3 AC解
/**
* 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) {
ListNode prehead=new ListNode(-1);
ListNode p=prehead;
while(head!=null){
if(head.next==null || head.next.val!=head.val){
p.next=head;
p=head;
} else{
while(head.next!=null && head.next.val==head.val){
head=head.next;
}
}
head=head.next;
}
p.next=null;
return prehead.next;
}
}