java链表实现

package Test2;

import Test.Node;

/**

  • Created by Administrator on 2019/4/28.
    */
    public class LinkList {
    class Node{
    private int data;
    private Node next;
    public Node(int data){
    this.data=data;
    }
    }
    private Node head;
    public void add(int data){
    Node newNode=new Node(data);
    if(headnull){
    head=newNode;
    return ;
    }
    Node temp = head;
    while (temp.next!=null){
    temp=temp.next;
    }
    temp.next=new Node(data);
    }
    //遍历链表
    public void print(Node node){
    if(node
    null){
    return;
    }
    Node temp = node;
    while (temp!=null){
    System.out.print(temp.data+",");
    temp=temp.next;
    }
    }

     public static void main(String[] args){
         LinkList list=new LinkList();
         for(int i=0;i<=5;i++){
             list.add(i);
         }
         list.print(list.head);
         System.out.println("head.data:" + list.head.data);
    
         int length=list.getLength();
         System.out.println("length:"+length);
    
         Node newHead= list.reverseList(list.head);
         list.print(newHead);
    
     }
     //获取链表长度
    

    public int getLength(){
    int length=0;
    Node temp =head;
    while (temp!=null){
    length++;
    temp=temp.next;
    }
    return length;
    }
    //删除指定节点
    public boolean deleteNode(Node node){
    Node cur=head;
    Node pre=head;
    while (cur.data!=node.data){
    if(cur.next==null){
    return false;
    }else {
    pre=cur;
    cur=cur.next;
    }
    }
    //如果是头节点
    if (cur.equals(head)){
    head=cur.next;
    }else {
    pre.next=cur.next;
    }
    return true;
    }
    //链表反转
    public Node reverseList(Node head){
    Node pre=null;
    Node next=null;
    while (head!=null){
    next=head.next;
    head.next=pre;
    pre=head;//指针后移
    head=next;
    }
    return pre;

    }

    //判断链表是否有环环
    public boolean hasCycle(Node head){
    if(head==null){
    return false;
    }
    Node first=null;
    Node second=null;
    while (head.next!=null){

     }
     return true;
    

    }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值