前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 206. Reverse Linked List

LeetCode 206. Reverse Linked List

原创
作者头像
大学里的混子
修改2018-10-29 17:04:40
2970
修改2018-10-29 17:04:40
举报
文章被收录于专栏:LeetCodeLeetCode

206. Reverse Linked List

Reverse a singly linked list.

Example:

代码语言:javascript
复制
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

解法一:

代码语言:javascript
复制
public ListNode reverseList(ListNode head) {
    if (head == null || head.next ==null) return head;
    ListNode pre = null;
    ListNode cur = head;
    ListNode next = head.next;
    while (cur !=null&&next !=null){
        cur.next = pre;
        pre = cur;
        cur = next;
        next = next.next;
    }
    cur.next = pre;
    return cur;
}

解法二:

这个解法与解法一的区别在于对next何时进行更新,如何更新。

代码语言:javascript
复制
public ListNode reverseList(ListNode head) {
    if (head == null || head.next ==null) return head;
    ListNode pre = null;
    ListNode cur = head;
    ListNode next;
    while (cur !=null){
        next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    return pre;
}

注意细节的处理。

扩展:反转双向链表

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 206. Reverse Linked List
    • 解法一:
      • 解法二:
        • 扩展:反转双向链表
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档