左程云基础班——单链表(带头结点)
链表结点
public class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
题目一:反转单向链表
public static Node ReverseList(Node head) {
Node pre = head.next;
head.next = null;
Node next = null;
while (pre != null) {
next = pre.next;
pre.next = head.next;
head.next = pre;
pre = next;
}
return head;
}
题目二:打印两个链表的公共部分
public static void printCommon(Node head1, Node head2) {
Node p = head1.next;
Node q = head2.next;
Node com = new Node(-1);
com.next = null;
while (p != null && q != null) {
if (p.value < q.value)
p = p.next;
else if (p.value > q.value)
q = q.next;
else {
System.out.print(p.value + " ");
p = p.next;
q = q.next;
}
}
}
题目三:判断一个链表是否为回文结构
public static boolean isPalindromList(Node head) {
Node cur = head.next;
Stack<Node> stack = new Stack<>();
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
cur = head.next;
while (cur != null) {
if (cur.value != stack.pop().value)
return false;
cur = cur.next;
}
return true;
}
题目四:将单向链表按某值划分成左边小、中间相等、右边大的形式
方法一:用三个链表分别保存,再合并
public static Node SmallerEqualBigger_1(Node head, int pivot) {
if (head.next == null) {
return head;
}
Node small_head = new Node(-1);
small_head.next = null;
Node small_tail = small_head;
Node equal_head = new Node(-1);
equal_head.next = null;
Node equal_tail = equal_head;
Node big_head = new Node(-1);
big_head.next = null;
Node big_tail = big_head;
Node res = head;
head = head.next;
res.next