本系列博文,将围绕以下几个方面:
Java单链表基本操作:
(一)顺序查找;
(二)指定位置增加节点;
(三)删除当前节点;
(四)单链表反转;
(五)输出倒数第K个节点;
(六)删除重复节点;
(七)排序
(八)合并两个排序单链表;
(九)交换相邻节点的值;
(十)O(n)时间内查找单链表的中间节点
(十一)逆序(从尾至头)输出单链表
(十二)判断单链表是否有环
(十三)判断两个链表是否相交
(十四)已知一个单链表中存在环,求进入环中的第一个节
本节讲述最基础的顺序查找,主要熟悉一下单链表的属性和基本操作。
/*
* 查找值为num的元素位置,没有返回-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;
}
}
当然,这里调用了定义好的Node,定义如下:
public class Node {
int data;
Node next;
Node(int data){
this.data=data;
}
}
以及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();
}
}