剑指offer——56.删除链表中重复的结点

来源:互联网 发布:psv重构数据库365 编辑:程序博客网 时间:2024/06/05 23:41

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

代码

思路:需要三个指针,第一个指针first的next指向头结点,第二个指针pre指向first,确保每次指向的是重复结点的前一个结点,第三个指针head来遍历,遇到重复结点,则向后,直到找到当前结点不等于下一个结点时,将pre的next指向head。

function deleteDuplication(pHead){    // write code here    if(pHead==null||pHead.next==null) return pHead;    var first={        val:0,        next:pHead    }    var head=pHead,pre=first;    while(head!=null&&head.next!=null){        if(head.val==head.next.val){            while(head.next&&head.next.val==head.val){                head=head.next;                           }            pre.next=head.next;        }else{            pre.next=head;            pre=pre.next;        }        //pre=head;        head=head.next;    }    return first.next;}