给定排序的链表,删除所有重复,使每个元素只出现一次。 例如, 给定1-> 1-> 2,return1-> 2。 给定1-> 1-> 2-> 3-> 3,return1-> 2-> 3。
/** * 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 *temp = head; if (head == NULL) return NULL; if ( head != NULL && head->next == NULL) return head; while (temp != NULL &&temp->next != NULL){ if (temp->val == temp->next->val ){ temp->next = temp->next->next; } else temp = temp->next; } return head; } };
给定排序的链表,删除所有具有重复数字的节点,只留下原始列表中不同的数字。 例如, 给定1-> 2-> 3-> 3-> 4-> 4-> 5,return1-> 2-> 5。 给定1-> 1-> 1-> 2-> 3,return2-> 3。
/** * 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) { if(head == NULL || head->next == NULL) return head; ListNode *newHead = new ListNode(0);//新建一个链表,这样就可以实现头结点为NULL的情况了 newHead->next = head; ListNode *pre = newHead; ListNode *cur = head; while (cur != NULL && cur->next != NULL){ if (cur->val != cur->next->val) pre = cur; else{ while (cur->next != NULL && cur->val == cur->next->val) cur = cur->next; pre->next = cur->next;//前驱节点的后继等于最后相等节点的后继 } cur = cur->next; } return newHead->next; } };
原文:http://www.cnblogs.com/Kobe10/p/6357985.html