《剑指offer》:[57]删除链表中重复的结点

来源:互联网 发布:linux hba卡查看 编辑:程序博客网 时间:2024/05/22 06:19
题目:在一个排序的链表中,如何删除重复的结点?

例如,在图a中重复结点被删除之后,链表如图b所示。


方案:这个题应该说是比较简单的,不在赘述,主要利用三个指针,就可以解决这个问题。
具体实现代码:
#include <iostream>using namespace std;struct ListNode{int data;ListNode *next;};ListNode *pHead=NULL;ListNode *pEnd=NULL;void CreateList(){int data;cin>>data;while(0!=data){ListNode *pNode=new ListNode;pNode->data=data;pNode->next=NULL;if(pHead==NULL)//空链表{pHead=pNode;pEnd=pNode;}else//非空链表;{// 插入在头结点;if(pHead->data > data ){pNode->next=pHead;pHead=pNode;}// 插入位置在非头结点;else{ListNode *p=pHead;while(p->next&& p->data<data)p=p->next;pNode->next=p->next;p->next=pNode;}}cin>>data;}}void DeleteDuplication(ListNode **head)//必须**,因为有可能删除头结点;{if(head==NULL || *head==NULL)return ;ListNode *preNode=NULL;ListNode *pNode=*head;while(pNode!=NULL){ListNode *pNext=pNode->next;bool needdelete=false;if(pNext!=NULL && pNext->data==pNode->data)needdelete=true;if(!needdelete){preNode=pNode;pNode=pNode->next;}else{int data=pNode->data;//记录下要删除的值;ListNode *tobedel=pNode;while(tobedel!=NULL && tobedel->data==data){pNext=tobedel->next;delete tobedel;tobedel=NULL;tobedel=pNext;}if(preNode==NULL)*head=pNext;elsepreNode->next=pNext;pNode=pNext;}}}void show(ListNode *head){while(head){cout<<head->data<<" ";head=head->next;}cout<<endl;}int main(){CreateList();DeleteDuplication(&pHead);show(pHead);system("pause");return 0;}

运行结果:



1 0