首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >LinkedList - 206. Reverse Linked List

LinkedList - 206. Reverse Linked List

作者头像
ppxai
发布2020-09-23 17:23:12
发布2020-09-23 17:23:12
34800
代码可运行
举报
文章被收录于专栏:皮皮星球皮皮星球
运行总次数:0
代码可运行
  1. Reverse Linked List

Reverse a singly linked list.

Example:

代码语言:javascript
代码运行次数:0
运行
复制
**Input:** 1->2->3->4->5->NULL
**Output:** 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

思路:

翻转链表,本来不想记录了,但是是链表系列中的“hello world”,有纪念意义,主要有两种方法,迭代和递归。 注意不要断链。

代码:

java:

代码语言:javascript
代码运行次数:0
运行
复制
/**

 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    // iterative
   /* public ListNode reverseList(ListNode head) {
        if (head == null) return head;
        
        ListNode curr = head;
        ListNode prev = null;
        
        while (curr != null) {
            ListNode temp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = temp;
        }
        
        return prev;
    }*/
    
  
    // recursive 
    public ListNode reverseList(ListNode head) {
        return reverseListInt(head, null);
    }

    private ListNode reverseListInt(ListNode head, ListNode newHead) {
        if (head == null)
            return newHead;
        ListNode next = head.next;
        head.next = newHead;
        return reverseListInt(next, head);
    }
}```
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年07月25日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档