閱讀948 返回首頁    go 阿裏雲 go 技術社區[雲棲]


[LeetCode]83.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.

【題意】

給定一個有序鏈表,刪除所有重複元素,使得每個元素隻出現一次。

【分析】

【代碼1】

/*********************************
*   日期:2014-01-28
*   作者:SJF0115
*   題號: Remove Duplicates from Sorted List
*   來源:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/
*   結果:AC
*   來源:LeetCode
*   總結:
**********************************/
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if(head == NULL){
            return head;
        }
        //記錄上一節點的值
        int preVal = head->val;
        ListNode *pre = head,*cur = head->next;
        while(cur != NULL){
            //如果相同則刪除cur節點
            if(cur->val == preVal){
                pre->next = cur->next;
                cur = pre->next;
            }
            else{
                preVal = cur->val;
                pre = cur;
                cur = cur->next;
            }
        }
        return head;
    }
};
int main() {
    Solution solution;
    int A[] = {1,1,1,4,4,6};
    ListNode *head = (ListNode*)malloc(sizeof(ListNode));
    head->next = NULL;
    ListNode *node;
    ListNode *pre = head;
    for(int i = 0;i < 6;i++){
        node = (ListNode*)malloc(sizeof(ListNode));
        node->val = A[i];
        node->next = NULL;
        pre->next = node;
        pre = node;
    }
    head = solution.deleteDuplicates(head->next);
    while(head != NULL){
        printf("%d ",head->val);
        head = head->next;
    }
    return 0;
}


最後更新:2017-04-03 12:54:51

  上一篇:go HTTP消息頭
  下一篇:go [LeetCode]25.Reverse Nodes in k-Group