内容:
1、链表基本结构
2、反转链表
3、打印两个有序链表的公共部分
4、判断一个链表是否为回文结构
5、单向链表划分区域
6、复制含有随机指针节点的链表
7、两个链表相交相关问题
1、链表基本结构
1 // 单向链表: 2 public static class Node { 3 public int value; 4 public Node next; 5 public Node(int data) { 6 this.value = data; 7 } 8 } 9 10 // 双向链表: 11 public static class DoubleNode { 12 // 双向链表的节点 13 public int value; 14 public DoubleNode last; // 前一个节点 15 public DoubleNode next; // 后一个节点 16 17 public DoubleNode(int data) { 18 this.value = data; 19 } 20 } 21 22 // 输出链表: 23 public static void printLinkedList(Node node) { 24 // 打印单向链表 25 System.out.print("Linked List: "); 26 while (node != null) { 27 System.out.print(node.value + " "); 28 node = node.next; 29 } 30 System.out.println(); 31 } 32 33 public static void printDoubleLinkedList(DoubleNode head) { 34 // 输出双向链表 35 System.out.print("Double Linked List: "); 36 DoubleNode end = null; 37 while (head != null) { 38 System.out.print(head.value + " "); 39 end = head; 40 head = head.next; 41 } 42 System.out.print("| "); 43 while (end != null) { 44 System.out.print(end.value + " "); 45 end = end.last; 46 } 47 System.out.println(); 48 } 49 50 // 求链表长度: 51 public static int getLinkListLength(Node head) { 52 int length = 0; 53 while (head != null) { 54 length++; 55 head = head.next; 56 } 57 return length; 58 } 59 60 // 数组和链表之间的转换: 61 // convert the linklist to array 62 public static int[] LinkListToArray(Node head) { 63 if (head == null) { 64 return null; 65 } 66 int length = getLinkListLength(head); 67 int[] arr = new int[length]; 68 int cur = 0; 69 while (head != null) { 70 arr[cur++] = head.value; 71 head = head.next; 72 } 73 74 return arr; 75 } 76 77 // convert the array to linklist 78 public static Node ArrayToLinkList(int[] arr) { 79 if (arr == null || arr.length == 0) { 80 return null; 81 } 82 Node head = new Node(arr[0]); 83 Node n = head; 84 for (int i = 1; i < arr.length; i++) { 85 n.next = new Node(arr[i]); 86 n = n.next; 87 } 88 89 return head; 90 }
2、反转链表
问题描述:
反转单向链表和双向链表
要求时间复杂度: O(N) 额外空间复杂度: O(1)
3、打印两个有序链表的公共部分
问题描述:
给定两个有序链表的头指针head1和head2 打印两个链表的公共部分
4、判断一个链表是否为回文结构
问题描述:
给定一个链表的头节点head, 请判断该链表是否为回文结构。 例如: 1->2->1, 返回true
1->2->2->1, 返回true 15->6->15, 返回true 1->2->3, 返回false
进阶: 如果链表长度为N, 时间复杂度达到O(N), 额外空间复杂度达到O(1)
5、单向链表划分区域
6、复制含有随机指针节点的链表
7、两个链表相交相关问题