题解 | #删除链表中重复的结点#
删除链表中重复的结点
https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef
/* 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* res = new ListNode(0); //在链表前加一个表头 res->next = pHead; ListNode* cur = res; while(cur->next != NULL && cur->next->next != NULL){ //遇到相邻两个节点值相同 if(cur->next->val == cur->next->next->val){ int temp = cur->next->val; //将所有相同的都跳过 while (cur->next != NULL && cur->next->val == temp) cur->next = cur->next->next; } else cur = cur->next; } //返回时去掉表头 return res->next; } };
注意加表头的方法,以及新建 一个遍历用的当前节点,遇到下一个节点和下下个节点相同,则删去相同的所有节点