https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/
1、题目要求:从已排序的链表里面删除重复的元素,使得每个元素只出现一次。
例:如果给定链表为:1->1->2,则返回1->2.
如果给定链表为:1->1->2->3->3,则返回1->2->3.
2、解题思路:因为链表已排序,则其重复的元素都是相邻的,所以只要比较当前结点与其下一结点是否相同即可。
/**
* 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) {
ListNode *result;
ListNode *temp, *tempNext;
if(!head) return NULL; //注意此时应该返回NULL,而不是result,因为result是ListNode类型,不是一个空指针,
result= head;
temp= head;
tempNext= temp->next;
while(temp&&tempNext) //注意循环结束的条件,只要有一个结点为空就结束循环;
{
if(temp->val==tempNext->val)
{
temp->next= tempNext->next; //如果有相等的结点的情况
tempNext= temp->next;
}
else
{
temp= tempNext;
tempNext= temp->next;
}
}
return result;
}
};