标签:toc 链表 from ima original ref inf tno delete
Given the head
of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现
的数字。
输入: 1->2->3->3->4->4->5
输出: 1->2->5
就是要把所有的重复的节点全部干掉!!。一个不留
p指向虚头,p.next 指向head
通过p来寻找是否存在data重复的节点,再通过q来寻找下一个不重复的节点。
/**
* 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 {
public ListNode deleteDuplicates(ListNode head) {
ListNode ret = new ListNode(0, head);
ListNode p = ret;
ListNode q ;
while(p.next!=null){
if(p.next.next!=null&&p.next.val==p.next.next.val){
q = p.next.next;
while(q!=null&&q.next!=null&&q.val==q.next.val){
q =q.next;
}
p.next =q.next;
}
else{
p = p.next;
}
}
return ret.next;
}
}
【数据结构】算法 Remove Duplicates from Sorted List 2 删除排序链表中的重复元素
标签:toc 链表 from ima original ref inf tno delete
原文地址:https://www.cnblogs.com/dreamtaker/p/14513364.html