本来挺容易的一道题,做起来就有很多问题,解决了之后,也感觉到自己的一些进步
首先要排除一些好解决的问题,链表结点就容易出现一些问题
最重要的就是当headPtr节点为NULL了,这时候就退出了,但是headBefore的值可能还要放入ret链表中去
在最后headPtr和headBefore两个节点的值比较的过程之中,分两个的值相等与不相等,进行后续处理得出最后的结果
首先ret:指向返回链表首结点
retPtr:指向返回链表的末尾节点,用来增长链表
pHeadPtr:指向pHead链表,用来移动判断
pHeadBefore:指向pHead链表,用来与pHeadPtr判断出来不想等的值,就把这个值产生新的节点加入ret
总体思路就是
1、先讨论链表为NULL的和链表只有一个结点的,将这两种情况排除之后,就是判断值pHeadBefore->value和pHeadPtr->value是否相等
2、不相等,就加入pHeadBefore->value;相等就移动pHeadPtr,直到不相等,使得pHeadBefore=pHeadPtr,pHeadPtr=pHeadPtr->next
代码如下:
#include<iostream> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; class Solution { public: ListNode* deleteDuplication(ListNode* pHead) { if (pHead == NULL) { return NULL; } //最后的返回链表 ListNode* ret = NULL; // ListNode* retPtr = NULL; //现链表的前一个节点 ListNode* pHeadBefore = pHead; //指向现节点 ListNode* pHeadPtr = pHead->next; //retPtr = ret; while (pHeadPtr != NULL) { if (pHeadPtr->val != pHeadBefore->val) { if (ret == NULL) { ret = new ListNode(pHeadBefore->val); retPtr = ret; } else { retPtr->next = new ListNode(pHeadBefore->val); retPtr = retPtr->next; } pHeadBefore = pHeadPtr; pHeadPtr = pHeadPtr->next; if (pHeadPtr == NULL) { retPtr->next= new ListNode(pHeadBefore->val); } } else { while(pHeadPtr != NULL && pHeadPtr->val == pHeadBefore->val) { pHeadPtr = pHeadPtr->next; } if (pHeadPtr != NULL) { pHeadBefore = pHeadPtr; pHeadPtr = pHeadPtr->next; if (pHeadPtr == NULL) { if (ret != NULL) { retPtr->next = new ListNode(pHeadBefore->val); } } } } } if (ret == NULL) { //只有一个节点的情况 if (pHeadBefore->next == NULL) { return new ListNode(pHeadBefore->val); } } return ret; } }; void printListNode(ListNode* root) { if (root == NULL) { cout<<"NULL"<<endl; } while (root != NULL) { cout<<root->val<<" "; root = root->next; } cout<<endl; } int main() { ListNode l1(1); ListNode l2(2); ListNode l3(3); ListNode l4(3); ListNode l5(4); ListNode l6(4); ListNode l7(5); l1.next = &l2; l2.next = &l3; l3.next = &l4; l4.next = &l5; l5.next = &l6; l6.next = &l7; printListNode(&l1); printListNode(Solution().deleteDuplication(&l1)); return 0; }