问题:
给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
示例:
输入:head = [1,2,3,3,4,4,5]
输出:[1,2,5]
输入:head = [1,1,1,2,3]
输出:[2,3]
思想:
利用双端队列对链表节点进行添加和删除
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
LinkedList<Integer> repmax = new LinkedList<Integer>();
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return null;
ListNode cur = head;
ListNode ans = head;
int t = 101;
while(cur!=null){
if(!repmax.isEmpty()&&repmax.peekLast()!=cur.val&&cur.val!=t){
repmax.addLast(cur.val);
cur = cur.next;
continue;
}
else if(!repmax.isEmpty()&&repmax.peekLast()==cur.val){
t = cur.val;
repmax.pollLast();
cur = cur.next;
continue;
}
else if(cur.val==t){
t = cur.val;
cur = cur.next;
continue;
}
repmax.addLast(cur.val);
cur = cur.next;
}
if(repmax.isEmpty()) return null;
while(!repmax.isEmpty()){
head.val = repmax.peekFirst();
repmax.pollFirst();
if(repmax.isEmpty()) break;
head = head.next;
}
head.next = null;
return ans;
}
}