单链表
- 单链表简述:
单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。
(1)链表中的数据是以结点来表示的。
(2)每个结点的构成:元素(数据元素的映象) + 指针(指示后继元素存储位置)。
(3)元素就是存储数据的存储单元,指针就是连接每个结点的地址数据。 指针就是引用。 - 链接存储方法
链接方式存储的线性表简称为链表(Linked List)。
(1)链表的具体存储表示为:
① 用一组任意的存储单元来存放线性表的结点(这组存储单元既可以是连续的,也可以是不连续的)
② 链表中结点的逻辑次序和物理次序不一定相同。为了能正确表示结点间的逻辑关系,在存储每个结点值的同时,还必须存储指示其后继结点的地址(或位置)信息(称为指针(pointer)或链(link))
(2)链式存储是最常用的存储方式之一,它不仅可用来表示线性表,而且可用来表示各种非线性的数据结构。 - 结点结构:
- 头指针head和终端结点
(1)单链表中每个结点的存储地址是存放在其前趋结点next域中,而开始结点无前趋,故应设头指针head指向开始结点。链表由头指针唯一确定,单链表可以用头指针的名字来命名。
(2)终端结点无后继,故终端结点的指针域为空,即NULL。 - 单链表的基本操作:
(1)头插法插入数据:
//头插法
public void InsertHead(int val){
Node cur = new Node(val);//cur 要插入的结点
cur.next = this.head.next;//连接尾巴
this.head.next = cur;//连接头
}
(2)尾插法插入数据:
class Linkedlist{ //链表
class Node{ //结点
int data; //结点的值
Node next; //后继结点的地址
public Node(){
this.data = -1;
this.next = null;
}
public Node(int val){
this.data = val;
this.next = null;
}
}
private Node head; //头指针 / 头引用
public Linkedlist(){
this.head = new Node();
}
//头插法
public void InsertHead(int val){
Node cur = new Node(val);//cur 要插入的结点
cur.next = this.head.next;
this.head.next = cur;
}
//尾插法
public void InsertTail(int val){
//先找到尾巴,尾结点即next域为空
Node cur = this.head;
while (cur.next != null){
cur = cur.next;//循环找到next为null的尾巴 指向下一个节点
}
Node temp = new Node(val);
cur.next = temp; //将数据插入
}
//打印单链表所有数据
public void Print(){
Node cur = this.head;
while (cur.next != null){
System.out.print(cur.next.data + " ");
cur = cur.next;
}
System.out.println();
}
}
public class Listlink {
public static void main(String[] args) {
Linkedlist linkedlist = new Linkedlist();
for (int i = 0; i < 10; i++) {
linkedlist.InsertTail(i);
}
linkedlist.Print();
linkedlist.InsertHead(-1);//头插法
linkedlist.Print();
linkedlist.InsertTail(10);//尾插法
linkedlist.Print();
}
}
//output:
0 1 2 3 4 5 6 7 8 9
-1 0 1 2 3 4 5 6 7 8 9
-1 0 1 2 3 4 5 6 7 8 9 10
(3)任意位置插入:
思想:先判断插入的位置是否合法,再进行插入。
//得到单链表长度
public int GetLength(){
int count = 0;
Node cur = this.head;
while (cur.next != null){
cur = cur.next;
count++;
}
System.out.println(count);
return count;
}
//任意位置插入数据
public void InsertPos(int pos, int val){
//判断pos 位置的合法性
if (pos < 0){
return;
}
Node cur = this.head;
Node temp = new Node(val);
int count = 0;
while (cur.next != null && count == pos){
cur = cur.next;
count++;
}
temp.next = cur.next;
cur.next = temp;
//使用for循环
/*if(pos < 0 || pos > getLength()) {
return;
}
Entry cur = this.head;
for (int i = 0; i <= pos-1; i++) { //pos-1 即为它要插入位置的前驱
cur = cur.next;
}
Entry entry = new Entry(val);
entry.next = cur.next;
cur.next = entry;*/
}
Over…单链表也是啊,画图先走清楚算法,然后再下手比较好,明天也要加油呀yayyayyya