养生 装修 购物 美食 感冒 便秘 营销 加盟 小吃 火锅 管理 创业 搭配 减肥 培训 旅游

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

时间:2024-10-13 07:28:48

顺序查找基本思想是:从表的一端开始,顺序扫描线性表,依次将扫描到的结点关键宇和给定值K相比较。若当前扫描到的结点关键字与K相等,则查找成功;若扫描结束后,仍未找到关键字等于K的结点,则查找失败。

工具/原料

JAVA程序开发软件

方法/步骤

1、publicclassSeqSearch{publicstaticvoidmain(String[]args){Nodehead=ListNode.getSingleList();ListNode.printList(head);intnum=9;intid=newSeqSearch().searchNumId(head,num);System.out.println("要查找的元素位置为:"+id);}publicintsearchNumId(Nodehead,intnum){intid=1;while(head!=null&&head.data!=num){head=head.next;id++;}if(head==null)id=-1;returnid;}}

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

2、调用定义好的Node,定义如下:publicclassNode{intdata; Nodenext;Node(intdata){this.data=data; }}

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

3、调用定义好的ListNode,定义如下:publicclassLis隋茚粟胫tNode{publicstaticNodegetSi荏鱿胫协ngleList(){Nodehead=newNode(3);Nodenode1=newNode(6);Nodenode2=newNode(8);Nodenode3=newNode(6);Nodenode4=newNode(2);head.next=node1;node1.next=node2;node2.next=node3;node3.next=node4;node4.next=null;returnhead;}publicstaticvoidprintList(Nodenode){System.out.print("List:");while(node!=null){System.out.print(node.data+"-->");node=node.next;}System.out.println();}}

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

© 一点知识