在一个排序的链表中,删除重复的结点,返回链表头指针

1.遍历链表

2.双重循环遍历,外循环遍历链表,假设外循环当前结点为cur,内循环从cur开始遍历,若碰到与cur所指结点相同,则删除这个重复结点。

import java.util.Hashtable;

public class DelDup {
    public static void main(String[] args){
        Node n1=new Node(2);
        Node n2=new Node(3);
        Node n3=new Node(5);
        Node n4=new Node(9);
        Node n5=new Node(9);
        n1.next=n2;
        n2.next=n3;
        n3.next=n4;
        n4.next=n5;
        //Node n=new DelDup().delDup(n1);
        Node n=new DelDup().delDup2(n1);
        while (n!=null){
            System.out.print(n.data+" ");
            n=n.next;
        }

    }
    //方法1.遍历链表
    public Node delDup(Node head){
        //保存前一结点的指针
        Hashtable<Integer,Integer> table = new Hashtable<Integer, Integer>();
        Node tmp=head;
        Node pre=null;
        while(tmp!=null) {
            if (table.containsKey(tmp.data)){
                pre.next=tmp.next;
            }else{
                table.put(tmp.data,1);
                pre=tmp;
            }
            tmp=tmp.next;
        }
        return head;

    }
    //方法2:双重循环遍历

    public Node delDup2(Node head){
        Node p=head;
        while(p!=null){
            Node q=p;
            while(q.next!=null){
                if(p.data==q.next.data){
                    q.next=q.next.next;
                }else{
                    q=q.next;
                }
            }
            p=p.next;
        }
        return head;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值