remove-duplicates-from-sorted-list-ii
来源:互联网 发布:伊甸园eden知乎 编辑:程序博客网 时间:2024/06/14 07:34
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.
本来是一道水题,结果彻底被教做人了。也反应了我的链表操作不太熟悉!
本题看起来虽然简单但是许多细节要注意!
首先是要记录头结点,其次是链表链接是要在不删除的情况下载连接,连接的时候,不要直接用p浅拷贝,因为p中的next值很容易造成错误,本来这条链是没有连起来的,结果连起来了。
注意结点的移动和结点的修改的区别。p->next = .., p = p->…。!
#include <iostream>using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };ListNode *deleteDuplicates(ListNode *head) { ListNode * pp = new ListNode(-1); pp->next = head; ListNode * p = head; ListNode * ans=NULL; int first = 1; while (p) { ListNode * pt = p ; int flag = 0; while(pt->next&&pt->val==pt->next->val) { pt->next=pt->next->next; flag = 1; } if(!flag) { pp->next = new ListNode(p->val); pp=pp->next; p=p->next; if(first) { ans = pp; first = 0; } } else { p = p->next; } } return ans;} void printList(ListNode* head) { ListNode* tmp = head; while(tmp) { cout<<tmp->val<<" "; tmp = tmp->next; } cout<<endl;}int main() { int t; cin>>t; while(t--) { cout<<"请输入要输入链表的长度\n"; int n; cin>>n; int a; cin>>a; ListNode* head = new ListNode(a); ListNode* p = head; for (int i=1;i<n;i++) { cin>>a; ListNode* tmp = new ListNode(a); p->next = tmp; p=p->next; } cout<<"处理前的链表为:\n"; printList(head); cout<<"处理后的链表为:\n"; head = (*deleteDuplicates)(head); printList(head); }}
0 0
- LeetCode: Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove duplicates from sorted list II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II
- js删除数组元素、清空数组的简单方法
- 遗迹系列 -【学渣告诉你】到底神马是傅里叶级数!
- JS 提交form表单
- informix-dbschema
- IntelliJ IDEA For Mac 快捷键
- remove-duplicates-from-sorted-list-ii
- Redis中持久化的两种方法详解
- 打包后的ipa怎么上传到appstore
- 判断字符串A中是否有B字符串!(其中A字符串是用“,”拼接成的).
- Java内部类详解
- android广播接收者实例_app状态监听
- linux 开启独立iptables日志
- JavaScript 判断闰年
- MVP模式在Android开发中的应用