Clairezz_的博客

Never give up!

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

题目:

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;
}
};


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭