标签:
题目:在一个排序的链表中,如何删除重复的结点?例如,在图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; else preNode->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; }
运行结果:
标签:
原文地址:http://blog.csdn.net/gogokongyin/article/details/51776732