在链表中查找一个元素用顺序查找的方法

 时间:2026-02-12 22:20:57

1、public class SeqSearch {

    public static void main(String[] args) {

        Node head=ListNode.getSingleList();

        ListNode.printList(head);

        int num=9;

        int id=new SeqSearch().searchNumId(head,num);

        System.out.println("要查找的元素位置为:"+id);

    }

    public int searchNumId(Node head,int num){

        int id=1;

        while(head!=null&&head.data!=num){

            head=head.next;

            id++;

        } 

        if(head==null) id=-1;

        return id;

    }

}

在链表中查找一个元素用顺序查找的方法

2、调用定义好的Node,定义如下:

public class Node {    

         int data;    

         Node next;   

         Node(int data){

                   this.data=data;   

          } 

}

在链表中查找一个元素用顺序查找的方法

3、调用定义好的ListNode,定义如下:

public class ListNode {

    public static Node getSingleList(){

        Node head=new Node(3);

        Node node1=new Node(6);

        Node node2=new Node(8);

        Node node3=new Node(6);

        Node node4=new Node(2);

        head.next=node1;

        node1.next=node2;

        node2.next=node3;

        node3.next=node4;

        node4.next=null;

        return head;

    }

    public static void printList(Node node){

        System.out.print("List:");

        while(node!=null){

            System.out.print(node.data+"-->");

            node=node.next;

        }

        System.out.println();

    }

}

在链表中查找一个元素用顺序查找的方法

  • 微信中北京本地宝能为我们提供哪便民服务?
  • 牛轧糖的做法最佳配方步骤图
  • ArcMap的Add-in及Soe开发总结
  • 京东金融怎么设置是否接收系统消息通知
  • arcgis建立缓冲区
  • 热门搜索
    逆向行驶怎么处罚 我的世界工作台怎么用 重庆旅游攻略景点必去 眼睫毛怎么变长 百里奚简介 潜伏之赤途攻略 未上锁的房间攻略 奥迪a8怎么样 imax怎么读 哈尔滨雪乡旅游攻略