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);
}
}