- 题目:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
- 思路:
- 当我们碰到一个节点,往后看下一个,是不是和他相同,如果相同,那么一直往后找到不同于这个值的点,作为当前点
- 代码:
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; */ class Solution { public: ListNode* deleteDuplication(ListNode* pHead) { ListNode* head = pHead; ListNode* preNode = NULL; if (!pHead) return NULL; while(pHead && pHead->next) { //cout << "pHead" << pHead->val << endl; //当我们碰到一个节点,往后看下一个,是不是和他相同,如果相同,那么一直往后找到不同于这个值的点,作为当前点 if (pHead->next) { if (pHead->next->val == pHead->val) { ListNode* temp = pHead; while (temp && temp->val == pHead->val) { temp = temp ->next; } if (preNode) preNode->next = temp; else head = temp; pHead = temp; } else { preNode = pHead; pHead = pHead -> next; } } } return head; } };
剑指offer 57. 删除链表中重复的结点
猜你喜欢
转载自blog.csdn.net/Alexia23/article/details/104094187
今日推荐
周排行