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
.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <iostream> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if (head == NULL) { return NULL; } ListNode Header(10); ListNode *Tail = &Header; ListNode *Next = NULL; bool IsSingle = true; while(head->next != NULL) { IsSingle = false; Next = head->next; if (head->val != Next->val) { Tail->next = new ListNode(head->val); Tail = Tail->next; } head = Next; } if (IsSingle) { return new ListNode(head->val); } if (Tail->val != head->val) { Tail->next = new ListNode(head->val); } return Header.next; } };
LeetCode_Remove Duplicates from Sorted List
原文地址:http://blog.csdn.net/sheng_ai/article/details/45049165