给定一个已排序的链表的头 head
, 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
示例 1:
输入:head = [1,2,3,3,4,4,5] 输出:[1,2,5]
示例 2:
输入:head = [1,1,1,2,3] 输出:[2,3]
思路:三个指针,一次遍历,遇到重复节点删除即可
代码:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*///三个指针 一次遍历class Solution {
public:ListNode* deleteDuplicates(ListNode* head) {if(head==nullptr){return head;}ListNode * pre = new ListNode(0,head);ListNode * start = pre;ListNode * end = pre;ListNode * end_pre = pre;start = start->next->next;end = end->next;int flag = 0;while(start!=nullptr){if(start->val == end->val){end->next = start->next;start = start->next;flag = 1;}else{if(flag==0){end = end ->next;start = start->next; end_pre = end_pre->next; }else{end_pre->next = end_pre->next->next;end = end->next;start = start->next;flag = 0;}}}if (flag==1){end_pre->next = end_pre->next->next;end = end->next;}return pre->next;}
};