题目描述
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinctnumbers from the original list.
For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.
解题思路:
1)首先记录当前结点指向的值tmp
2)如果下一结点不等于该值,则将该结点连入返回的链表
3)若下一结点等于该值,则找到下一个不等于该值的结点
4)然后进行下次操作
5)p->next = NULL目的是断开p当前指向结点与head后不符合的结点断开
例如:1->2->2 此时phead->next = 1, p 指向的是1->2->2 且p指向1 p->next = NULL 就断开了不符合条件的2->2 此时phead 指向的链表只包含1
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 10 class Solution { 11 public: 12 ListNode *deleteDuplicates(ListNode *head) { 13 if(head == NULL) 14 return NULL; 15 ListNode *phead = new ListNode(0); 16 ListNode *p = phead; 17 while(head != NULL) 18 { 19 int tmp = head->val; 20 if(head->next == NULL || head->next->val != tmp) 21 { 22 p->next = head; 23 p = p->next; 24 head = head->next; 25 } 26 else 27 { 28 while(head->next != NULL && head->next->val == tmp) 29 { 30 head = head->next; 31 } 32 head = head->next; 33 } 34 } 35 p->next = NULL;//断开p与head后面不符合要求的结点的联系 36 return phead->next; 37 } 38 }; 39 ListNode *CreateList(int n) 40 { 41 ListNode *head; 42 ListNode *p,*pre; 43 int i; 44 head=(ListNode *)malloc(sizeof(ListNode)); 45 head->next=NULL; 46 pre=head; 47 for(i=1;i<=n;i++) 48 { 49 p=(ListNode *)malloc(sizeof(ListNode)); 50 cin>>p->val; 51 pre->next=p; 52 pre=p; 53 } 54 p->next=NULL; 55 56 return head->next; 57 } 58 /*-------------------------输出链表-----------------------------------*/ 59 void PrintList(ListNode *h) 60 { 61 ListNode *p; 62 63 p=h;//不带空的头结点 64 while(p) 65 { 66 cout<<p->val<<" "; 67 p=p->next; 68 cout<<endl; 69 } 70 } 71 int main() 72 { 73 int n1; 74 int x; 75 ListNode *h1; 76 cout<<"输入链表1的结点数目"<<endl; 77 cin>>n1; 78 h1 = CreateList(n1); 79 cout<<"链表1为:"<<endl; 80 PrintList(h1); 81 Solution s; 82 h1 = s.deleteDuplicates(h1); 83 cout<<"删除全部重复结点后链表1为:"<<endl; 84 PrintList(h1); 85 }