zoukankan      html  css  js  c++  java
  • 删除链表中重复的节点

    因为这个程序快累死老子了,细节处理很麻烦
    package Solutions;

    import java.util.ArrayList;

    /**
    * Created by hu on 2015/12/12.
    */
    /*
    * 删除链表中重复的结点
    *在一个排序的链表中,存在重复的结点,
    * 请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
    * 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
    *
    * */
    public class solution32 {
    public static ListNode deleteDuplication(ListNode pHead)
    {
    //如果pHead为空或者只有一个节点的时候,那么就返回头结点
    if (pHead==null||pHead.next==null){
    return pHead;
    }
    //p是遍历链表的节点
    ListNode p=pHead.next;
    ListNode pre=pHead;
    ListNode q=p.next;
    while (q!=null){
    if(p.val==q.val){
    q=q.next;
    }else {
    if(p.next==q){
    pre=p;
    p=q;
    q=q.next;
    }else if (p.next!=q){
    if(pre.val==p.val){
    return deleteDuplication(q);
    }
    pre.next=q;
    p=q;
    q=q.next;
    }
    }
    }
    if(p.next!=null){
    if (pHead.val==p.val){
    return null;
    }else {
    pre.next=null;
    }
    }
    if(pHead.val==pHead.next.val){
    pHead=pHead.next.next;
    }
    return pHead;
    }
    public static void main(String[] args){
    ListNode node1=new ListNode(1);
    ListNode node2=new ListNode(1);
    ListNode node3=new ListNode(2);
    ListNode node4=new ListNode(3);
    ListNode node5=new ListNode(3);
    ListNode node6=new ListNode(4);
    ListNode node7=new ListNode(5);
    ListNode node8=new ListNode(5);
    node1.next=node2;
    node2.next=node3;
    node3.next=node4;
    node4.next=node5;
    node5.next=node6;
    node6.next=node7;
    node7.next=node8;
    //ListNode res=node1;
    ListNode res=deleteDuplication(node1);
    while (res!=null){
    System.out.print(res.val+" ");
    res=res.next;
    }
    }
    }
  • 相关阅读:
    [转] websocket新版协议分析+python实现 & websocket 通信协议
    [转] html5演示
    新浪网内部讲师进阶研习会之笔记
    css3 animation属性
    【转】python多线程编程
    搭建selenium自动化环境步骤
    win10下搭建QTP测试环境
    cocos2dx跨平台环境
    Cocos2dx运行win32工程
    原型模式(prototype)
  • 原文地址:https://www.cnblogs.com/hujingwei/p/5041086.html
Copyright © 2011-2022 走看看