82. Remove Duplicates from Sorted List II
来源:互联网 发布:js点击效果 编辑:程序博客网 时间:2024/06/14 17:41
题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
题目分析:
1、边界情况:链表为空,链表长度为1
2、对于每一个节点都要与下一个节点对比,若两节点的值相同,指针向后移动;若该节点与下一节点的值不同,但是该节点与上一节点值相同,指针向后移动
思路:
1、处理边界情况
2、设置一个标识符,记录当前节点与之前的相邻节点值是否相同。每次判断一个节点需要判断:是否与前一个节点值相同,是否与下一个节点值相同
3、设置一个新的头节点,每当遇到可以保留的节点,将新链表的尾节点指向该链表
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* deleteDuplicates(ListNode* head) { if (head == nullptr || head->next == nullptr) return head; ListNode* dummy = new ListNode(0); ListNode* p = dummy; bool flag = true; while (head->next != nullptr){ if (head->next->val == head->val || (flag == 0)){ flag = (head->next->val != head->val) ? true : false; head = head->next; } else{ p->next = head; p = p->next; head = head->next; p->next = nullptr; } } if (flag) p->next = head; return dummy->next; }};
0 0
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 【NOIP2015】洛谷2679 子串
- python挑战之level 32
- 电影的分级制度介绍
- AlertDialog
- Fibonacci数列求解方法总结
- 82. Remove Duplicates from Sorted List II
- Android再次按back键退出
- HDU 5534 Partial Tree (完全背包)
- 收藏文章
- 用secureCRT连接Ubuntu
- Android开发之OAuth(一)
- poj-3723【图的最小生成树+并查集】
- HDU 4821 字符串hash
- APUE学习笔记4——第六章——系统数据文件和信息