最困难的事情就是认识自己。–希腊
一、从尾到头打印链表
问题描述
方法一:原地翻转
思路分析
- 首先创建两个节点prev current,一个初始化为空,另一个是指向head,这两节点的作用为保存前一个节点和当前节点
- 通过循环,改变节点的指向,改变指向的操作如下:首先创建一个节点来保存下一个节点,将当前节点的next指向前一个节点prev,由于新节点的缘故,current后面部分的链表并没有丢失,只需要将前一个节点prev指针变成current,再将当前节点指针改变成新节点即可(current=newNode),类似递归思想,最后的结束条件是current==null,表示后面没有节点了
- 最后循环遍历,加入到数组中,思想就是这样,在改变指向的操作中每个人的操作顺序不一样,遍历时候采用开始节点也就不一样,比如我在while中使用的是current.next!=null 的话,length和下面就不能使用prev了,
代码实现
java版本
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
//Reverse
ListNode prev = null;
ListNode current = head;
int length = 0;
while(current != null) {
ListNode newNode = current.next;
current.next = prev;
prev = current;
current = newNode;
length = length + 1;
}
int[] result = new int[length];
for (int i = 0; i < result.length; i++) {
result[i] = prev.val;
prev = prev.next;
}
return result;
}
}
方法二:辅助栈
这个思路就很清晰了,先进后出,刚好能够满足我们链表的反转
代码如下:
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> stack = new LinkedList<Integer>();
while(head != null) {
stack.addLast(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
for(int i = 0; i < res.length; i++)
res[i] = stack.removeLast();
return res;
}
}
二、反转链表
问题描述:
代码实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode current = head;
while(current!=null){
ListNode newNode = current.next;
current.next = prev;
prev = current;
current = newNode;
}
return prev;
}
}
运行截图
三、复杂链表的复制
题目描述:
思路分析:
赖皮写法直接上代码
代码实现:
class Solution {
public Node copyRandomList(Node head) {
if(head == null) return null;
Node cur = head;
Map<Node, Node> map = new HashMap<>();
// 3. 复制各节点,并建立 “原节点 -> 新节点” 的 Map 映射
while(cur != null) {
map.put(cur, new Node(cur.val));
cur = cur.next;
}
cur = head;
// 4. 构建新链表的 next 和 random 指向
while(cur != null) {
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
// 5. 返回新链表的头节点
return map.get(head);
}
}