单链表是一种线性数据结构,每个元素都存放在链表的一个结点中,结点之间由指针串联在一起,这样就形成了一条如同链的结构,固称作链表。**所谓单链表顾名思义就是只能单方向遍历的链表。**如下图所示:
单链表的基本操作
单链表最基本的操作包括创建一个单链表、向单链表中插入结点、从单链表中删除结点等。
java版本的实现
package dataStructure;
class Node{
int data;
Node next = null;
//创建节点
public Node(int d) {
data = d;
next = null;
}
}
public class SingleList {
//单链表的头结点
Node head;
public SingleList() {
head = null;
}
//计算单链表长度
int ListLength() {
int length = 0;
Node currentNode = head;
// 遍历单链表
while(currentNode != null) {
length++;
currentNode = currentNode.next;
}
return length;
}
//打印单链表
void Print() {
Node cur = head;
if(cur == null ) {
System.out.print("null");
}
while(cur != null) {
System.out.print(cur.data+"->");
cur = cur.next;
}
System.out.println();
}
//单链表的插入
Node Insert(Node node,int position) {
if(head == null ) {
head = node;
return head;
}
int size = ListLength();
if(position < 1 || position > size+1) {
System.out.println("违法插入");
return head;
}
if(position == 1) {
node.next = head;
head = node;
return head;
}else {
int count = 1;
Node it = head;
//找到插入的位置的前一个结点
while(count < position-1) {
it = it.next;
count++;
}
node.next = it.next;
it.next = node;
}
return head;
}
//删除单链表指定的结点
Node deleteNode(int position) {
Node it = head;
int size = ListLength();
if(position > size || position < 1) {
System.out.println("违法删除");
return head;
}
if(position == 1) {
Node currentNode = head.next;
head = currentNode;
return currentNode;
}else {
int count = 1;
while(count < position-1) {
it = it.next;
count++;
}
it.next =it.next.next;
}
return head;
}
//删除整个单链表
Node deleteSingList() {
Node cur = head;
Node rear = head;
head = null;
while(cur != null) {
rear = cur.next;
cur= null;
cur = rear;
}
return head;
}
public static void main(String[] args) {
SingleList list = new SingleList();
list.Insert(new Node(1),2);
list.Insert(new Node(3),2);
list.Insert(new Node(2),2);
list.Print();
list.deleteNode(1);
list.Print();
list.deleteSingList();
list.Print();
}
}