[数据结构]手动实现单链表

package com.darrenchan;

public class MyList {
    /**
     * 插入(头插法)
     */
    public static void headInsert(ListNode head, ListNode newhead){
        ListNode old = head;
        head = newhead;
        head.next = old;
    }
    /**
     * 插入(尾插法)
     */
    public static void tailInsert(ListNode tail, ListNode newtail){
        ListNode old = tail;
        tail = newtail;
        tail.next = null;
        old.next = tail;
    }
    /**
     * 遍历查找
     */
    public static int find(ListNode head, int value){
        int index = -1;
        int count = 0;
        while(head != null){
            if(head.value == value){
                index = count;
                return index;
            }
            head = head.next;
            count++;
        }
        return index;
    }
    /**
     * 插入节点(p后面插入s)
     */
    public static void insert(ListNode p, ListNode s){
        ListNode next = p.next;
        p.next = s;
        s.next = next;
    }

    /**
     * 删除节点
     */
    public static void delete(ListNode head, ListNode q){
        if(q != null && q.next != null){
            ListNode p = q.next;
            q.value = p.value;
            //删除q.next
            q.next = p.next;
            p = null;
        }
     //处理删除最后一个元素的情况
if(q.next == null){ while(head != null){ if(head.next != null && head.next == q){ head.next = null; break; } head = head.next; } } } public static void main(String[] args) { ListNode node1 = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(3); node1.next = node2; node2.next = node3; node3.next = null; traverse(node1); ListNode newhead = new ListNode(0); headInsert(node1, newhead); traverse(newhead); ListNode newtail = new ListNode(4); tailInsert(node3, newtail); traverse(newhead); System.out.println(find(newhead, 4)); ListNode node = new ListNode(5); insert(newtail, node); traverse(newhead); delete(newhead, node3); traverse(newhead); } /** * 遍历 */ public static void traverse(ListNode head){ while(head != null){ System.out.print(head.value + " "); head = head.next; } System.out.println(); } }

 

转载于:https://www.cnblogs.com/DarrenChan/p/9535540.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值