码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 83:Remove Duplicates from Sorted List

时间:2015-12-12 08:22:29      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

Subscribe to see which companies asked this question

 //利用两个结点指针cur和temp,cur表示当前结点,temp表示下一个结点
 //如果当前结点的值与下一个结点的值相等,则让当前结点的指针指向下一个结点的下一个结点即可
class Solution {
public:
	ListNode* deleteDuplicates(ListNode* head) {
		if (head == NULL || head->next == NULL)  
			return head;
		else
		{
			ListNode* cur = head;
			ListNode* temp = head->next;
			while (temp){
				if (cur->val == temp->val)
				{
					cur->next = temp->next;
					temp = cur->next;   //注意此时前一个temp的位置已经找不到,应该利用cur移动到cur的下一个结点
				}
				else
				{
					cur = cur->next;    //循环后移
					temp = temp->next;
				}
			}
			return head;
		}
	}
};

技术分享

LeetCode 83:Remove Duplicates from Sorted List

标签:

原文地址:http://blog.csdn.net/geekmanong/article/details/50266313

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!