1. 程式人生 > >leetcode 83 Remove Duplicates from Sorted List

leetcode 83 Remove Duplicates from Sorted List

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

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

連結串列是基本的資料結構,無論是面試還是工作中,都會經常遇到,可惜之前一直沒能重視起來。本題是easy的級別,但是連結串列的訪問和刪除功底太薄弱,看了別人的答案才能做出來。由於是排好序的連結串列,所以本題只需要在非空節點的條件下判斷相等的情況並刪除相應的節點(指向下一節點)即可,程式碼記錄如下:

/**
 * 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 *p = head;
        if(NULL == head || NULL == head->next)
            return head;
        while(NULL != p->next)
        {
          if(p->val == p->next->val)
          {
              ListNode *tmp = p->next;
              p->next = tmp->next;
              //delete tmp;   //delete here?
              continue;
          }
          p = p->next;         
        }
        return head;
    }
};