链表介绍
链表也是线性结构,但是和数组不同,链表中的数据并不存储在连续的内存值中。元素通过指针连接在一起。
链表的优势:
- 动态大小
- 容易删增
劣势:
- 不允许随机访问,只允许顺序访问
- 需要额外的内存来存储指针
表示方法:
链表由指向链表第一个节点的指针表示。链表的节点叫头节点。如果链表为空,则头也为空。
每个节点包含两部分:数据和指针。
public class LinkedList
{
Node head;
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
}
}
}
第一个简单的java语言链表,
代码如下:
public class LinkedList
{
Node head;
static class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
llist.head.next = second;
second.next = third;
}
}
其中,Node head是用来声明一个链表的头节点;在class Node 中,声明链表的结构,一个数据data, 一个下一个节点。并声明一个初始化构造器。
在主函数中,我们创建一个链表。并用
- llist.head = new Node(1);创建第一个节点;
- Node second = new Node(2);创建第二个节点并将数据赋值为2;
- Node third = new Node(3);用来创建第三个节点,并将数据赋值为3;
接下来开始连接不同的节点:
llist.head.next = second连接第一个和第二个节点;
second.next = second连接第二个和第三个节点;
链表遍历:
public class LinkedList
{
Node head;
static class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
llist.head.next = second;
second.next = third;
llist.printLinkedList();
}
public void printLinkedList()
{
Node n = head;
while(n!=null)
{
System.out.println(n.data);
n = n.next;
}
}
}
其中在链表中,n = head表示指向head的节点。再通过while循环来便利内容打印