首页 > 其他 > 详细

(链表)删除链表的重复元素

时间:2017-01-30 11:42:52      阅读:172      评论:0      收藏:0      [点我收藏+]
  • 题目一:
    给定排序的链表,删除所有重复,使每个元素只出现一次。
    
    例如,
    给定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

     

  • 思路:这个和上一个题目又不一样了,是删除出现重复元素的所有,只留下不同的数字。对于一个链表而言,我们可以设定一个当前节点的前驱节点。当相邻元素不同时,直接下一个节点,但是当相邻节点相同的时候,让前驱节点等于第一个出现相邻元素节点的前一个节点,然后循环处理相邻元素节点,最后让prv->next = cur->next.等于最后一个相同节点的next。这里要特殊处理一下头结点。因为当前节点的头结点可能是NULL。
  • 代码
    /**
     * 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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!