82. Remove Duplicates from Sorted List II
来源:互联网 发布:ai mac中文版免费下载 编辑:程序博客网 时间:2024/06/05 16:23
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.
思路
类似于83题,不过这里重复元素都要删掉,涉及到头节点可能会删掉的问题,需要定义一个辅助节点
代码(C)
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* deleteDuplicates(struct ListNode* head) { if (NULL == head) return head; struct ListNode* helper = (struct ListNode*)malloc(sizeof(struct ListNode));//辅助指针 helper->next = head; struct ListNode* pre = helper; struct ListNode* cur = head; while (cur) { while (cur->next != NULL && pre->next->val == cur->next->val) cur = cur->next; if (pre->next == cur)//没有重复的,则pre 和 cur都向后移动一位 pre = pre->next; else pre->next = cur->next;//有重复的话,pre的下一个节点指向当前节点的下一个节点,相当于中间都删除了 cur = cur->next; } return helper->next;}
循环那段不明白的话画幅图走一遍就清楚了。
0 0
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- SQLAlchemy_定义(一对一/一对多/多对多)关系
- python安装教程及环境配置
- 【51单片机学习过程记录】4矩阵键盘
- AsyncTask工作原理解析
- 整理常用的十个git命令
- 82. Remove Duplicates from Sorted List II
- 链表的一些简单操作
- QT的信号与槽机制介绍
- [总结贴]虚拟机安装MAC OS X 10.10
- MySQL不支持FULL JOIN, INTERSECT和MINUS(except)的替代方法
- 专题总结:数据结构总结【转】
- aaaaaaaaa
- python--list中append()与extend()用法
- KinectSDK + Unity3D学习总结