[leetcode][list] Remove Duplicates from Sorted List II

原创 2015年07月07日 11:22: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:
    ListNode* deleteDuplicates(ListNode* head) {
	if (NULL == head || NULL == head->next) return head;
	ListNode *p = head, *tail = NULL;//p指向当前节点,初始化为原链表第一个节点;tail指向新链表的最后一个节点,要初始化为NULL
	head = NULL;//!!!head指向新链表的第一个节点,要初始化为NULL
	while (p != NULL){
		int val = p->val;
		if (p->next == NULL || p->next->val != val){//不是重复节点
			if (NULL == tail){
				tail = p;
				head = p;
			}
			else{
				tail->next = p;//将当前节点连入新链表
				tail = tail->next;//更新tail指针
			}
			p = p->next;//更新当前节点指针
		}
		else {//是重复节点
			while (p != NULL && p->val == val){//删除所有重复节点
				ListNode *tmp = p;
				p = p->next;
				delete tmp;
			}
		}
	}
	if (tail != NULL) tail->next = NULL;//!!!新链表最后一个节点的next为NULL
	return head;
}
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode82:Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct num...

Remove Duplicates from Sorted List II--LeetCode

题目: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinc...

LeetCode | Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb...

[LeetCode] Remove Duplicates from Sorted List II

给定一个已经排序的单链表,删除所有有相同数字的节点,只留下原始链表中的不同数字。

【一天一道LeetCode】#82. Remove Duplicates from Sorted List II

一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目...

LeetCode - 82. Remove Duplicates from Sorted List II

这一道题目主要是链表的操作,一开始因为情况比较复杂,把自己绕晕了,所以没想到这道题目的解法,后来看了答案才觉得自己解起来确实很难解出。这道题目对于链表的操作比较复杂,所要考虑的情况也很多,最大的一个技...

leetcode_82_Remove Duplicates from Sorted List II

思路: 大致思路就是,遍历链表找出重复元素的子列并删除重复元素子列,当然,第一个元素开始有重复元素的话比较特种,需要特殊考虑。删除子列的过程稍微有点绕,题目倒是不难理解。

[leetcode 82]Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb...

LeetCode 82. Remove Duplicates from Sorted List II pre指针,首元素的处理

题目 题意 注意 思路 代码 结果题目 Given a sorted linked list, delete all nodes that have duplicate numbers, leav...

[leetcode] 82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)