单链表——删除重复的相邻元素

学习单链表的使用

此处用到空节点,作为一种提取所用节点,区别废节点的工具,可以按照条件筛选节点。
头节点作为一个链表的基准,很多时候不好先对头动手,此时如果可以另外选择一个空基准的话,不失为一个好的选择,这个举例在此处可能不太合理,哈哈哈

package demo0716;

public class Single_Node {
    Node head = null;

    /**
     * 单链表 节点 实体类定义
     */
    class Node {
        //属性
        public int data;
        public Node next;

        //方法
        public Node(int data) {
            this.data = data;
        }
    }

    /**
     * 尾插法
     */
    public void addlast(int data) {
        Node cur = this.head;
        Node newnode = new Node(data);
        if (head == null) {
            head = newnode;
        } else {
            while (cur.next != null) {
                cur = cur.next;
            }
            cur.next = newnode;
        }
    }

    /**
     * 打印链表
     */
    public void display() {
        Node cur = this.head;
        if (cur == null) {
            return;
        }
        while (cur != null) {
            System.out.print(cur.data + " ");
            cur = cur.next;
        }
    }
    /**
     * 带返回参数打印链表
     */
    public void display2(Node head) {
        Node cur = head;
        if (cur == null) {
            return;
        }
        while (cur != null) {
            System.out.print(cur.data + " ");
            cur = cur.next;
        }
    }

    /**
     * 利用空的头节点,删除链表中重复的元素
     * 重复元素指的是:相邻两个元素是相同的!
     * @param
     */
    public Node samepoint(int data) {
        Node cur = this.head;
        //空头
        Node emptyhead = new Node(-1);
        //空头替身
        Node tmp = emptyhead;
        
        while (cur !=null) {
            if (cur.next != null && cur.data == cur.next.data) {
                while (cur.next != null && cur.data == cur.next.data) {
                    cur = cur.next;
                }
                cur = cur.next;
            } else {
                tmp.next = cur;
                tmp = tmp.next;
                cur = cur.next;
            }
        }
        return emptyhead.next;
    }

    public static void main(String[] args) {
        Single_Node demo = new Single_Node();
        System.out.println("**** 尾插法 ****");
        demo.addlast(1);
        demo.addlast(2);
        demo.addlast(2);
        demo.addlast(3);
        demo.addlast(4);
        demo.addlast(5);
        demo.display();
        System.out.println();
        System.out.println("**** XX法 ****");
        Node same = demo.samepoint(2);
        demo.display2(same);
    }
}

结果如下:
在这里插入图片描述
是一种思路,目前这个阶段就是熟练使用,顺便积累思路的过程!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值