
方法1: 这道easy题两个方法我都没有解出来,主要原因是感觉还是接触链表题目太少。第一个方法是iterate。这个方法关键在于要新建一个prev node,初始化为null。具体思路是curr node的next指向prev node,然后在向右移动curr node和pre node。时间复杂度n,空间复杂度1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while(curr != null){
ListNode temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return prev;
}
}
方法2: recursion。其实链表题的recursion逻辑并不是很难想,主要是正确的写出这个逻辑,这中间会比较绕。时间复杂度n,空间复杂度n。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head ==null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}
总结:
- 这是一道非常经典的题目,虽然是easy题,但是学到了不少链表swap之类的操作
博客围绕一道链表相关的LeetCode简单题展开,介绍了两种解法。迭代法需新建prev node,将curr node的next指向prev node并右移节点,时间复杂度n,空间复杂度1;递归法逻辑不难想但实现较绕,时间和空间复杂度均为n。通过此题学到链表swap操作。
425

被折叠的 条评论
为什么被折叠?



