一、线性链表:用一组任意的存储单元存储线性表的数据元素
结点表示:class LNode{
int data;
LNode next;
}
二、代码理解
import java.util.*;
class LNode{
int data;
LNode next;
Scanner in = new Scanner(System.in);
public LNode(int data) { //创建一个结点
this.data = data;
}
public void createList(LNode L,int n) { //创建一个长度为n的链表,头节点为L
L.next = null;
for(int i = 1;i<n;i++) {
LNode P = new LNode(in.nextInt());
L.next = P;
L =L.next;
}
}
public LNode getElem(LNode L,int i) { //在链表L中查找第i个元素的值
LNode P = L.next;
int j = 1;
while((P!=null)&&j<i) {
P = P.next;
++j;
}
return P;
}
public void ListInsert(LNode L,int i,LNode e) { //在链表L中第i个位置插入元素e
LNode P = L.next;
int j = 1;
while((P!=null)&&j<i) {
P = P.next;
++j;
}
e.next = P.next;
P.next = e;
}
public void ListDelet(LNode L,int i) { //在链表L中删除第i个结点
LNode P = L.next;
int j = 1;
while((P!=null)&&j<i) {
P = P.next;
++j;
}
P.next = P.next.next;
}
}
public class LinkedLists {
int data;
LNode next;
Scanner in = new Scanner(System.in);
public LNode(int data) { //创建一个结点
this.data = data;
}
public void createList(LNode L,int n) { //创建一个长度为n的链表,头节点为L
L.next = null;
for(int i = 1;i<n;i++) {
LNode P = new LNode(in.nextInt());
L.next = P;
L =L.next;
}
}
public LNode getElem(LNode L,int i) { //在链表L中查找第i个元素的值
LNode P = L.next;
int j = 1;
while((P!=null)&&j<i) {
P = P.next;
++j;
}
return P;
}
public void ListInsert(LNode L,int i,LNode e) { //在链表L中第i个位置插入元素e
LNode P = L.next;
int j = 1;
while((P!=null)&&j<i) {
P = P.next;
++j;
}
e.next = P.next;
P.next = e;
}
public void ListDelet(LNode L,int i) { //在链表L中删除第i个结点
LNode P = L.next;
int j = 1;
while((P!=null)&&j<i) {
P = P.next;
++j;
}
P.next = P.next.next;
}
}
public class LinkedLists {
public static void main(String[] args) {
// TODO Auto-generated method stub
LNode L = new LNode(10);
L.createList(L, 10); //创建长度为n的链表
// TODO Auto-generated method stub
LNode L = new LNode(10);
L.createList(L, 10); //创建长度为n的链表
LNode P = L.next;
for(int i = 1;i<=10;i++) { //遍历链表
System.out.print(P.data+" ");
L = P.next;
}
for(int i = 1;i<=10;i++) { //遍历链表
System.out.print(P.data+" ");
L = P.next;
}
LNode n = L.getElem(L, 5); //查找第5个结点
System.out.println();
System.out.print(n.data);
System.out.println();
System.out.print(n.data);
}
}
输入:1 2 3 4 5 6 7 8 9
输出:1 2 3 4 5 6 7 8 9
5
三、单链表的自反
public static Nodes reverseList(Nodes head) {
Nodes pre = null;
Nodes next = null;
while(head!=null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}