题目
反转单向链表
本题力扣有测试链接:https://leetcode.cn/problems/reverse-linked-list/
题解
就是修改指针指向,还需要一个next指针暂存下一个节点。照着代码对照例子走一遍,或者自己画图走一遍,就明白了,一定要过一遍例子!硬看会觉得抽象
时间复杂度&空间复杂度
时间复杂度:O(N)
空间复杂度:O(1)。这种简单的题目,就不要用容器了,比如放到栈中逆序一下,这样空间复杂度就是O(N),笔试可以,面试没分
代码
public Node reverseList(Node head) {
Node pre = null;
Node tmp = null;
while (head != null) {
tmp = head.next; // 暂存后继节点 cur.next
head.next = pre; // 反转引用
pre = head; // pre来到head
head = tmp; // head来到下一节点
}
return pre;
}
public class Node {
int val;
Node next;
Node(int val, Node next) {
this.val = val;
this.next = next;
}
}
例子