您的位置:首页 > 编程语言 > Java开发

java实现单链表的基本操作

2014-08-12 13:55 351 查看
package link;
/**
* 单链表模型:实现插入、删除、查找、反转、输出等操作
* @author USER
*
*/

//结点类
class Node{
protected int data; //结点数据
protected Node next;	//结点指针

//结点构造方法
public Node(int data) {
this.data=data;
}

public void print() {
System.out.print(data+" ");
}

}

//链表类
class Link{
public  Node head;//头结点
private int pos = 0;	//结点位置

public Link(){
this.head = null;
}

//插入一个头结点
public void addHeadNode(int data) {
Node node = new Node(data);
node.next = head;//此处head为null
head = node;//此处head为新加入的结点
}

//在任意位置index处插入一个结点,插入结点在index之后的那个结点
public void add(int index, int data) {
Node node = new Node(data);
Node previous = head;
Node current = head;
while (pos!=index) {
previous = current;
current = current.next;
pos++;
}
node.next = current;
previous.next = node;
pos = 0;
}

//在任意位置index处删除一个结点,删除的是第index个结点,不能删除第一个结点
public void delete(int index) {
Node previous = head;
Node current = head;
pos++;
while (pos!=index) {
previous = current;
current = current.next;
pos++;
}
previous.next = current.next;
pos = 0;
}

//删除头结点
public void deleteHead() {
Node temp = head;
head = temp.next;
}

//根据结点位置查找结点信息,注意:index是指第几个位置,pos是从0开始代表第一个位置
public Node findByPos(int index) {
Node current = head;
pos++;
while (pos != index) {
current = current.next;
pos++;
}
pos = 0;
return current;
}

//根据结点数据查找结点信息
public Node findByData(int data) {
Node current = head;
while (current.data != data) {
if (current.next == null) {
return null;
}else {
current = current.next;
}
}
return current;
}

//整个链表的长度
public  int length() {
int size = 0;
Node current = head;
while (current != null) {
current = current.next;
size++;
}
return size;
}

//显示整个链表
public void show() {
Node current = head;
while (current != null) {
current.print();
current = current.next;
}
System.out.println();
}

}

public class MySingleLinkList {
public static void main(String[] args) {
Link list = new Link();
list.addHeadNode(10);
list.show();//10

list.add(1, 12);
list.add(2, 13);
list.add(3, 14);
list.add(4, 15);
list.add(5, 16);
list.show();//10 12 13 14 15 16
System.out.println(list.length());//6

list.delete(2);
list.show();//10 13 14 15 16
list.delete(2);
list.show();//10 14 15 16
System.out.println(list.length());//4

list.deleteHead();
list.show();//14 15 16

System.out.println(list.findByPos(2).data);//15
System.out.println(list.findByPos(3).data);//16
System.out.println(list.findByData(15).data);//15
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: