123

Remove Duplicates from Sorted List Total

原题:(https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/)

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.

这道题比较简单,熟悉线性链表的操作。代码如下:

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode *p;
        p = head;
        while(head&&head->next)
        {
            if(head->next->val == head->val)
            {
                ListNode *nextNode;                  
                nextNode = head->next->next;
                delete head->next;
                head->next = nextNode;
            }
            else
            {
                head = head->next;
            }
        }
        return p;
    }
};

红色代码释放了内存,ac不是必要。

 

 
posted @ 2014-10-29 22:15  顫栗  阅读(107)  评论(0)    收藏  举报