实现单链表中的增删查改(2)

今天亲手写了一次单链表的增删查功能,实现了~

package link;
/*
 * 实现一个单链表的增删查改
 */

class Node<E>{
    Node<E>next;
    E data;
    public Node(E data){this.data=data;}
    public void display(){
        System.out.print(data+" ");
    }
}
public class LearnLink<E> {
    Node<E>head=null;
    int pos=0;

    /*增加一个头结点*/
    public void addFirstNode(E data){
        Node<E>node=new Node<E>(data);
        node.next=head;
        head=node;
    }

    /*向索引为index处增加一个新的数据*/
    public void addItemtoIndex(int index,E data){
        Node<E>node=new Node<E>(data);
        Node<E> current=head;
        Node<E> previous=head;//两个指针都是从头结点开始
        while(pos!=index){
            previous=current;       //当前结点比previous几点快一步
            current=current.next;
            pos++;      
        }
        node.next=current;
        previous.next=node; //插入node结点到current和previous之间
        pos=0;

    }


    /*直接向链表中添加一个值*/
    public void addDatatoLink(E data){
        Node<E> node=new Node<E>(data);
        Node<E> tmp=head;
        while(tmp.next!=null){
            tmp=tmp.next;   //当tmp结点为最后一个节点的时候
        }
        tmp.next=node;  //将node结点添加到tmp结点后面
    }

    /*删除链表中的第index个值*/
    public void deleteData(int index){
        Node<E>pre=head;
        Node<E>post=head;
        while(pos!=index){
            pre=post;
            post=post.next;
            pos++;
        }

        pre.next=post.next;//pre结点的指针直接指向post的下一个指针 跳过post将其删除
        pos=0;

    }


    /*根据index查找结点信息*/
    public Node<E> findNodebyIndex(int index){
        Node<E>current=head;
        while(pos!=index){
            current=current.next;
            pos++;
        }
        return current;
    }


    /*显示所有的结点信息*/
    public void displayAllNodes(){

        Node<E>current=head;
        while(current!=null){
            current.display();
            current=current.next;
        }
        System.out.println();
    }

    public static void main(String[] args){
        LearnLink<Integer> link=new LearnLink<>();
        link.addFirstNode(22);  
        link.addDatatoLink(25);
        link.addItemtoIndex(2,23);
        link.addItemtoIndex(3,24);
        link.addItemtoIndex(4,25);

        link.deleteData(3);
        link.displayAllNodes();
        Node node1 = link.findNodebyIndex(1);  
         System. out.println( "node1: " + node1. data);
        /*
         *     输出:
         *    22 25 23 25 //本来是22 25 23 24 25 删除了24
              node1: 25
         */

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值