本文共 2483 字,大约阅读时间需要 8 分钟。
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2Example 2:
Input: 1->1->2->3->3
Output: 1->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; ListNode* point = head; while(temp) { while(point != nullptr && point->val == temp->val) { point = point->next; } temp->next = point; temp = point; } return head; }};
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5Example 2:
Input: 1->1->1->2->3
Output: 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) { if(!head || !head->next) return head; ListNode* start = new ListNode(0); start->next = head; ListNode* pre = start; while(pre->next) { ListNode* cur = pre->next; while(cur->next && cur->next->val == cur->val) { cur = cur->next; } if(cur != pre->next) { pre->next = cur->next; } else { pre = pre->next; } } return start->next; }};
转载地址:http://vuzjn.baihongyu.com/