单链表----定义、增加节点、删除节点、遍历输出(java)

单链表的结构比较简单,图示如下:
这里写图片描述

单链表有很多个节点构成。每个节点由指针域和数值域构成,指针指向下一个节点的数值域。最后一个节点的指针指向的是NULL。

java实现单链表的一些基本的操作:

package test;
import javax.xml.soap.Node;
/**
 * 单链表的创建和增删改查 
 * @author duola
 */
public class SingleLinkList {
    public  Listnode head;
    public  Listnode current;

    // 添加节点
    public   void addnode(int data) {
        if (head == null) {
            head = new Listnode(data);
            current=head;
        }
        else {
            current.next=new Listnode(data);
            current=current.next;//移位
        }
    }


    // 节点类
    public  class Listnode {
        int value;
        Listnode next;
        Listnode(int x) {
            this.value = x;
        }
    }


    //遍历循环,打印链表的元素
    public  void printList(Listnode l) {
        if(l==null) return;
        current=l;
        if(current!=null){
            System.out.print(current.value+"\t");
            current=current.next;
            printList(current);//递归调用
        }
    }

    // 根据节点的data删除节点(仅仅删除第一个)  
    public void deleteNode(int data) {
        Listnode cur = head;
        Listnode pre=cur;//保存位置

        //找到目标元素的节点位置,cur
        while(cur.value!=data){
            if(cur.next==null){
                return;
            }
            pre=cur;
            cur=cur.next;
        }

        //判断cur的位置与头结点的关系
        if(cur==head){
            head=head.next;}
        else {
            pre.next=cur.next;
        }
    }

    //主方法
    public static void main(String [] args) {

        int[] a={1,2,3,5,6,5,8};
        int[] b={6,4,3,2,1};

        SingleLinkList l1=new SingleLinkList();
        SingleLinkList l2=new SingleLinkList();

        //在链表中插入元素
        for(int i=0;i<a.length;i++){
            l1.addnode(a[i]);
        }

        for(int j=0;j<b.length;j++){
            l2.addnode(b[j]);
        }

        //删除操作
        l1.deleteNode(5);

        //打印链表的元素
        l1.printList(l1.head);
        System.out.print("\n");
        l2.printList(l2.head);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值