力扣 206. 反转链表
206. 反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
思路一:三个指针迭代
三个指针往后移,当 cur 指针为空时跳出循环
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 // 三指针法 11 public ListNode reverseList(ListNode head) { 12 13 ListNode pre = null, cur = head, next = head; 14 // 遍历链表,每次修改并移动这三个指针 15 while(cur != null){ 16 next = cur.next; // 记录下个节点位置 17 cur.next = pre; // 指针转向 18 pre = cur; // 指针后移 19 cur = next; 20 } 21 return pre; 22 } 23 }
力扣测试时间为:0ms, 空间为39.8MB
复杂度分析:
时间复杂度:因为只扫描了一遍链表,所以时间复杂度为O(n)
空间复杂度为O(1)
思路二:递归方式
递归,先递归到最后一个结点,返回到上一层后让head.next.next指向head,让一个往后指的指针往回指,每次都返回链表的最后的那个节点
1 class Solution { 2 // 递归法 3 public ListNode reverseList(ListNode head) { 4 // 如果head为空,或者head.next返回空,直接返回head 5 if(head == null || head.next == null){ 6 return head; 7 } 8 // 获取到尾节点,即将来的头结点 9 ListNode p = reverseList(head.next); 10 // 让head的下个结点的指针指向自己 11 head.next.next = head; 12 // 让head.next为空 13 head.next = null; 14 // 返回反转链表后的头指针 15 return p; 16 } 17 }
力扣测试时间为:0ms, 空间为39.8MB
复杂度分析:
时间复杂度:需要遍历两次链表,一次是不断递归直到最后一个结点,另一次是从最后一个结点往前反转,所以时间复杂度为O(n)
空间复杂度:递归的深度为O(n),所以空间复杂度为O(n)
思路转自:
https://leetcode-cn.com/problems/reverse-linked-list/solution/fan-zhuan-lian-biao-by-leetcode/