题目描述
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.
解题思路:
定义两个指针pre、pNode
其中pNode负责向后查找下一连接在要返回链表的结点,其中pre负责每次记录某一个值得第一个结点。
如果pNode->val == pre->val,pNode就向下一结点移动,直至不相等pre->next = pNode
需要注意的是:如果pNode->next == NULL即pNode为最后一个节点了,且值还相等则pre->next = NULL直接返回头指针
1 #include <iostream> 2 #include <malloc.h> 3 using namespace std; 4 struct ListNode { 5 int val; 6 ListNode *next; 7 ListNode(int x) : val(x), next(NULL) {} 8 }; 9 ListNode *CreateList(int n) 10 { 11 ListNode *head; 12 ListNode *p,*pre; 13 int i; 14 head=(ListNode *)malloc(sizeof(ListNode)); 15 head->next=NULL; 16 pre=head; 17 for(i=1;i<=n;i++) 18 { 19 p=(ListNode *)malloc(sizeof(ListNode)); 20 cin>>p->val; 21 pre->next=p; 22 pre=p; 23 } 24 p->next=NULL; 25 26 return head->next; 27 } 28 /*-------------------------输出链表-----------------------------------*/ 29 void PrintList(ListNode *h) 30 { 31 ListNode *p; 32 33 p=h;//不带空的头结点 34 while(p) 35 { 36 cout<<p->val<<" "; 37 p=p->next; 38 cout<<endl; 39 } 40 } 41 class Solution { 42 public: 43 ListNode *deleteDuplicates(ListNode *head) { 44 if(head == NULL) 45 return NULL; 46 ListNode *pre = head; 47 ListNode *pNode = head; 48 while(pNode != NULL) 49 { 50 while(pNode->val == pre->val) 51 { 52 if(pNode->next != NULL) 53 pNode = pNode->next; 54 else 55 { 56 pre->next = NULL; 57 return head; 58 } 59 } 60 pre->next = pNode; 61 pre = pre->next; 62 } 63 return head; 64 } 65 }; 66 int main() 67 { 68 int n1; 69 ListNode *h1; 70 cout<<"输入链表1的结点数目"<<endl; 71 cin>>n1; 72 h1 = CreateList(n1); 73 cout<<"链表1为:"<<endl; 74 PrintList(h1); 75 Solution s; 76 ListNode *h2; 77 h2 = s.deleteDuplicates(h1); 78 cout<<"去重后链表为:"<<endl; 79 PrintList(h2); 80 return 0; 81 }