Leetcode剑指Offer刷题指南:
解法一:辅助栈
class Solution {
public int[] reversePrint(ListNode head) {
//辅助栈
Deque<Integer> stack = new ArrayDeque<>();
int count = 0;
while (head != null) {
stack.push(head.val);
count++;
head = head.next;
}
//辅助数组
int[] ret = new int[count];
for (int i = 0; i < count; ++i) {
ret[i] = stack.pop();
}
return ret;
}
}
解法二:翻转链表
1.(带傀儡节点)
class Solution {
public int[] reversePrint(ListNode head) {
//翻转链表
ListNode newHead = null;
int count = 0;
while (head != null) {
ListNode tmp = head.next;
head.next = newHead;
newHead = head;
head = tmp;
count++;
}
int[] ret = new int[count];
int i = 0;
while (newHead != null) {
ret[i++] = newHead.val;
newHead = newHead.next;
}
return ret;
}
}
2.(不带傀儡节点)
class Solution {
public int[] reversePrint(ListNode head) {
//翻转链表(不带傀儡节点)
ListNode pre = null;
ListNode cur = head;
ListNode curNext = null;
int count = 0;
while (cur != null) {
curNext = cur.next;
cur.next = pre;
pre = cur;
cur = curNext;
count++;
}
int[] ret = new int[count];
int i = 0;
while (pre != null) {
ret[i++] = pre.val;
pre = pre.next;
}
return ret;
}
}
解法三:反向填充数据:计数器 + 从后向前遍历
class Solution {
public int[] reversePrint(ListNode head) {
ListNode node = head;
int count = 0;
//计数
while (node != null) {
++count;
node = node.next;
}
int[] ret = new int[count];
node = head;
//从后向前遍历,依次放入
for (int i = count - 1; i >= 0; --i) {
ret[i] = node.val;
node = node.next;
}
return ret;
}
}
解法一:反转链表(同上题法2中两种)
解法二:递归
class Solution {
public ListNode reverseList(ListNode head) {
//递归
if (head == null || head.next == null) {
return head;
}
ListNode node = reverseList(head.next);
head.next.next = head;
head.next = null;
return node;
}
}
解法一:回溯 + 哈希表
class Solution {
Map<Node, Node> map = new HashMap<Node, Node>();
public Node copyRandomList(Node head) {
//回溯 + 哈希表
if(head == null) {
return null;
}
if (!map.containsKey(head)) {
Node newHead = new Node(head.val);
map.put(head, newHead);
newHead.next = copyRandomList(head.next);
newHead.random = copyRandomList(head.random);
}
return map.get(head);
}
}
解法二:迭代 + 节点拆分
1.复制值相同,没有分配next和random的node
2.将两条链连接起来,复制random,将 node的random.next 复制给 node.next.random
3.将两条链断开,node.next -> node.next.next
class Solution {
//迭代 + 节点拆分
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
for (Node node = head; node != null; node = node.next.next) {
Node newNode = new Node(node.val);
newNode.next = node.next;
node.next = newNode;
}
for (Node node = head; node != null; node = node.next.next) {
Node newNode = node.next;
newNode.random = (node.random == null) ? null : node.random.next;
}
Node newHead = head.next;
for (Node node = head; node != null; node = node.next) {
Node newNode = node.next;
node.next = node.next.next;
newNode.next = (newNode.next == null) ? null : newNode.next.next;
}
return newHead;
}
}