LeetCode之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
*   来源:http://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;
}


LeetCode之Remove Duplicates from Sorted List

上一篇:C#PictureBox实现一直显示提示信息


下一篇:do {...} while (0) 在宏定义中的作用