- 003-从尾到头打印链表
递归法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
ArrayList<Integer> tmp = new ArrayList<>();
public int[] reversePrint(ListNode head) {
recur(head);
int[] res = new int[tmp.size()];
int i = 0;
for(Integer each: tmp){
res[i++]=each;
}
return res;
}
public void recur(ListNode head){
if(head==null){
return;
}else{
recur(head.next);
tmp.add(head.val);
}
}
}
- 因为原函数要求用数组而不是动态数组,所以只能额外再写一个递归函数;否则可以使用返回动态数组,使用addAll的方法;(注意结尾的null)
- 核心就是返回void,然后修改方法外的动态数组,如果null,就return;(void),否则就是先递归,再add;
- 时空复杂度: 遍历链表时间-O(n),栈递归空间:O(n)
辅助栈-先入后出
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
while(head !=null){
stack.push(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
int i= 0;
while(!stack.isEmpty()){
res[i++] = stack.pop();
}
return res;
}
}
- 一样都是O(n)
直接法
反正也是扫描两遍
可以直接先扫描一遍链表计算大小,然后分配数组,从最后面开始赋值
然后可以直接放进递归里面,进行赋值,在递归语句之前进行递增,末尾处进行数组的初始化,
后面的赋值都是栈里面存着的;
class Solution {
int[] res;
int i=0,j=0;
public int[] reversePrint(ListNode head) {
recur(head);
return res;
}
public void recur(ListNode head){
if(head==null){
res = new int[i];
return;
}else{
++i;
recur(head.next);
res[j++] = head.val;
}
}
}
时空复杂度一样
- 014-链表中倒数第k个结点
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode slow=head;
ListNode fast=head;
while(k-->1 && fast!=null){
fast = fast.next;
}
while(fast.next!= null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
快慢指针-1-2-3-4-5-6
k = 2; 因为快指针最后到的是倒数第一个的节点,所以快指针应该先走k-1个节点;
然后快指针最后应该到达最后一个节点,所以用next来作为终止条件
time O(n) space O(1)
- 015-反转链表
- 016-合并两个或k个有序链表
- 025-复杂链表的复制
- 036-两个链表的第一个公共结点
- 055-链表中环的入口结点
- 056-删除链表中重复的结点