#206 Reverse Linked List

Description

Given the head of a singly linked list, reverse the list, and return the reversed list.

Examples

Example 1:
在这里插入图片描述

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:
在这里插入图片描述

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

Constraints:

The number of nodes in the list is the range [0, 5000].
-5000 <= Node.val <= 5000

思路

他给了follow up,要用iterative和recursive两种方法做,iterative的方法很好像,类似于插入排序,每次都提取后面的一个node,挪到开始位置就好了。

recursive的方法感觉还需要写一下,放在一个函数里进行,终止条件是当前node或者node.next是null,然后先运行后续的节点交换,再交换当前node,举个例子来说,假设是

1 → 2 → 3 → 4 → 5

  • 处理1:
    • 处理2 :
      • 处理3:
        • 处理4:
          • 处理5: 5
        • 现有:4.next = (处理5中的)5
        • 令:(处理5中的)5.next = 4
        • 令:4.next = null
        • 处理4:5 → 4
      • 现有:3.next = (处理4中的)4
      • 令:(处理4中的)4.next = 3
      • 令:3.next = null
      • 处理3:5 → 4 → 3
    • 现有:2.next = (处理3中的)3
    • 令:(处理3中的)3.next = 2
    • 令:2.next = null
    • 处理2:5 → 4 → 3 → 2
  • 现有:1.next = (处理2中的)2
  • 令:(处理2中的)2.next = 1
  • 令:1.next = null
  • 处理1:5 → 4 → 3 → 2 → 1

代码

iterative

/**
 * 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 start = new ListNode();
        ListNode tmp = head;
        
        while(tmp != null) {
            ListNode next = tmp;
            tmp = tmp.next;
            
            next.next = start.next;
            start.next = next;
        }
        
        return start.next;
    }
}

recursive

/**
 * 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 newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值