单向链表
包含解决的问题:
- 求单链表中有效节点的个数
- 查找单链表中的倒数第k个结点 - 使用双指针实现 【新浪面试题】
- 单链表的反转 - 通过栈的方式实现
- 从尾到头打印单链表 - 方式1:递归实现 。 方式2:Stack栈实现
- 合并两个有序的单链表,合并之后的链表依然有序。
代码示例:
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class LinkedList {
private ListNode head;
public int getLength() {
int length = 0;
ListNode current = head;
while (current != null) {
length++;
current = current.next;
}
return length;
}
public ListNode findKthFromEnd(int k) {
if (k <= 0 || head == null)
return null;
ListNode fast = head;
ListNode slow = head;
for (int i = 0; i < k; i++) {
if (fast == null)
return null;
fast = fast.next;
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
public void reverse() {
if (head == null || head.next == null)
return;
ListNode prev = null;
ListNode current = head;
ListNode next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
public void reverseByStack() {
if (head == null || head.next == null)
return;
Stack<ListNode> stack = new Stack<>();
ListNode current = head;
while (current != null) {
stack.push(current);
current = current.next;
}
head = stack.pop();
current = head;
while (!stack.isEmpty()) {
current.next = stack.pop();
current = current.next;
}
current.next = null;
}
public void reversePrint() {
if (head == null)
return;
reversePrint(head);
}
private void reversePrint(ListNode node) {
if (node == null)
return;
reversePrint(node.next);
System.out.print(node.val + " ");
}
public void reversePrintByStack() {
if (head == null)
return;
Stack<ListNode> stack = new Stack<>();
ListNode current = head;
while (current != null) {
stack.push(current);
current = current.next;
}
while (!stack.isEmpty()) {
System.out.print(stack.pop().val + " ");
}
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode current = dummy;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
current.next = l1;
l1 = l1.next;
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
if (l1 != null) {
current.next = l1;
} else {
current.next = l2;
}
return dummy.next;
}
}