面试时链表解题的方法论
1)对于笔试,不用太在乎空间复杂度,一切为了时间复杂度
2)对于面试,时间复杂度依然放在第一位,但是一定要找到空间最省的方法
重要技巧:
1)额外数据结构记录(哈希表等)
2)快慢指针
1.反转链表
public calss ReverseList {
public static class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
public static Node reverseList(Node head) {
Node pre = null;
Node next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static class DoubleNode {
public int value;
public DoubleNode last;
public DoubleNode next;
public DoubleNode(int data) {
this.value = data;
}
}
public static DoubleNode reverseList(DoubleNode head) {
DoubleNode pre = null;
DoubleNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
head.last = next;
pre = head;
head = next;
}
return pre;
}
}
2.打印两个链表的有序部分
public static void printCommonPart(Node head1, Node head2) {
while (head1 != null && head2 != null) {
if (head1.value < head2.value) {
head1 = head1.next;
} else if (head1.value > head2.value) {
head2 = head2.next;
} else {
System.out.println(head1.value + " ");
head1 = head1.next;
head2 = head2.next;
}
}
}
3.判断一个链表是不是回文链表
方法一:(需要N的额外空间)
遍历链表,然后将数据存入栈中,最后再遍历一次链表,比较是否与栈中数据相等
public static boolean isP(Node head) {
Stack<Node> stack = new Stack<>();
Node cur = head;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
while (head != null) {
if (head.value != stack.pop().value) {
return false;
}
head = head.next;
}
return true;
}
方法二:(需要N/2的额外空间)
使用快慢指针,快指针遍历到结尾时,慢指针刚好到达中间,然后再将慢指针后面的数存入栈中,再遍历N/2的链表即可
public static boolean isP(Node head) {
if (head == null || head.next == null) {