Remove Duplicates from Sorted List

来源:互联网 发布:集分宝淘宝购物怎么用 编辑:程序博客网 时间:2024/06/05 06:55

题目:

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.

题目大意:给定一个已经排序的链表,删除重复的元素。

思路:从head开始遍历,当遇到重复的节点记录下首次重复的节点,当两个相邻节点值不等时判断是否有记录重复的节点,如果有则需要删除操作,只需将首次记录的节点的next指向新的节点,如此,当循环结束时再处理一次标志位。代码如下:

class Solution {public:ListNode *deleteDuplicates(ListNode *head) {if(head == NULL)return NULL;ListNode *flag = NULL;ListNode *temp_head = head;while(temp_head->next){if(temp_head->val == temp_head->next->val){// First time repeat.if(flag == NULL){flag = temp_head;}}else{// Delete the repeated node.if(flag != NULL){flag->next = temp_head->next;flag = NULL;}}temp_head = temp_head->next;}if(flag != NULL){flag->next = NULL;}return head;}};

这道题的加强版:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

题目大意:删除所有重复的节点,所做的策略是节点替换,注意因为替换节点,所以需要重新set当前节点(为了防止野指针),而且最后处理标志位时,可能还需要遍历得到最后一个重复节点的前驱以便删除结尾处的节点。代码如下:
class Solution {public:ListNode *deleteDuplicates(ListNode *head) {if(head == NULL)return NULL;ListNode *flag = NULL;ListNode *temp_head = head;while(temp_head->next){if(temp_head->val == temp_head->next->val){// First time repeat.if(flag == NULL){flag = temp_head;}temp_head = temp_head->next;}else{// Delete the repeated node.if(flag != NULL){flag->val = temp_head->next->val;flag->next = temp_head->next->next;// Because use flag replace the temp_head so need to reset the temp_head;temp_head = flag;flag = NULL;}else{temp_head = temp_head->next;}}}if(flag != NULL){if(flag == head)head = NULL;else{// Search the last repeated node's previous.temp_head = head;while(temp_head->next != flag)temp_head = temp_head->next;temp_head->next = NULL;}}return head;}};

0 0
原创粉丝点击