[leetcode][list] Remove Duplicates from Sorted List II
来源:互联网 发布:杭州市行知幼儿园招聘 编辑:程序博客网 时间:2024/05/16 19:55
题目:
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
.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public://!!!head可能被删除//如何判读一个节点是否为重复节点?看当前节点和它后面的那个节点的val是否相同。一旦发现当前节点是重复节点,则删除该节点及其所有副本 ListNode* deleteDuplicates(ListNode* head) { if(NULL == head || NULL == head->next) return head; ListNode *pLast = NULL;//指向新链表最后一个节点 ListNode *p = head;//用于遍历链表 ListNode *headNew = NULL;//指向新链表第一个节点 while(p){ int value = p->val;//当前节点的val if(NULL == p->next || p->next->val != value){//当前节点不是重复节点,将当前节点连入新链表 if(NULL == headNew) headNew = p;//如果当前节点是原链表第一个无重复节点,该节点是新链表的第一个节点 else pLast->next = p;//如果当前节点不是新链表的第一个节点,将该节点连入新链表 pLast = p;//当前节点是新链表的最后一个节点 p = p->next;//更新遍历指针 } else{//当前节点是重复节点 while(p && p->val == value){//这些节点不是新链表的节点,将其释放 ListNode *tmp = p; p = p->next; delete tmp; } } } if(pLast) pLast->next = NULL;//新链表最后一个节点的next为NULL return headNew; }};
0 0
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II
- LeetCode-Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- LeetCode - Remove Duplicates from Sorted List II
- LeetCode | Remove Duplicates from Sorted List II
- LeetCode:Remove Duplicates from Sorted List II
- 【leetcode】Remove Duplicates from Sorted List II
- Leetcode: Remove Duplicates from Sorted List II
- leetcode Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- 读书笔记—面向物联网的传感器网络综述
- 弹出dialog后不可点击back返回,用广播退出所有activity
- ios中的nonatomic,atomic,assign,copy,retain等含义
- C++primer 4.4 数组指针和指针数组(转)
- HTML条件注释判断浏览器版本命令总结
- [leetcode][list] Remove Duplicates from Sorted List II
- 原生js写的贪吃蛇网页版游戏
- java代理模式
- 如何在Linux里安装chrome
- C++ 虚函数的定义
- VS2010最常用快捷键
- 常用的webservice接口
- svn版本控制在eclipse中用法详解
- (atoi)Leetcode第八题_String to Integer (atoi)