概述
这里记录一下单链表的一些操作,代码使用 Java 实现。
单链表
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class SinglyLinkedList {
// test
public static void main(String[] args) {
ListNode linkOne = initList(10, null);
ListNode linkTwo = initList(0, null);
// 构造 linkOne 和 linkTwo 两个链表
insertNodeInHead(linkOne, 10);
insertNodeInTail(linkTwo, 10);
// 打印链表
System.out.println("==== print ====");
System.out.println("==== linkOne ====");
printList(linkOne);
System.out.println();
printListRecur(linkOne);
System.out.println();
printReListRecur(linkOne);
System.out.println();
System.out.println("==== linkTwo ====");
printList(linkTwo);
System.out.println();
printListRecur(linkTwo);
System.out.println();
printReListRecur(linkTwo);
System.out.println();
// 逆序列表
System.out.println("==== reverse ====");
System.out.println("==== linkOne ====");
linkOne = reverse(linkOne);
printList(linkOne);
System.out.println();
linkOne = reverseRecur(linkOne);
printList(linkOne);
}
// 初始化单链表
public static ListNode initList(int val, ListNode next) {
return new ListNode(val, next);
}
// 头插法
public static void insertNodeInHead(ListNode head, int len) {
for (int i=0; i<len; i++)
{
ListNode node = new ListNode(i, null);
node.next = head.next;
head.next = node;
}
}
// 尾插法
public static void insertNodeInTail(ListNode head, int len) {
ListNode tail = head;
for (int i=1; i<=len; i++) {
ListNode node = new ListNode(i, null);
tail.next = node;
tail = node;
}
}
// 正向打印单链表,非递归
public static void printList(ListNode head) {
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
// 正向打印单链表,递归
public static void printListRecur(ListNode head) {
if (head == null)
return;
System.out.print(head.val + " ");
printListRecur(head.next);
}
// 反向打印单链表,只能递归
public static void printReListRecur(ListNode head) {
if (head == null)
return;
printReListRecur(head.next);
System.out.print(head.val + " ");
}
// 反转单链表,非递归
public static ListNode reverse(ListNode head) {
ListNode newHead = null, node = null;
while (head != null) {
node = head;
head = head.next;
node.next = newHead;
newHead = node;
}
return newHead;
}
// 反转单链表,递归
public static ListNode reverseRecur(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode newHead = reverseRecur(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
/* res
==== print ====
==== linkOne ====
10 9 8 7 6 5 4 3 2 1 0
10 9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9 10
==== linkTwo ====
0 1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1 0
==== reverse ====
==== linkOne ====
0 1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1 0
*/
总结
不忘初心,砥砺前行!