资讯专栏INFORMATION COLUMN

Reverse Linked List I II

刘永祥 / 1245人阅读

Reverse Linked List
Reverse a singly linked list.

click to show more hints.

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

非递归

public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode p=head,q=head.next,next=null;
        head.next=null;
        while(q!=null){
            next=q.next;
            q.next=p;
            p=q;
            q=next;
        }
        return p;
    }
}

2.递归

public class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode tmp=reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return tmp;
    }
}

Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

代码

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null||head.next==null) return head;
        ListNode dummy=new ListNode(0);
        dummy.next=head;
        ListNode pre=dummy,p=head;
        int count=1;
        while(count           
               
                                           
                       
                 

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69822.html

相关文章

  • [LeetCode] Reverse Linked List I & II

    Reverse Linked List Reverse a singly linked list. Note Create tail = null; Head loop through the list: Store head.next, head points to tail, tail becomes head, head goes to stored head.next; Return t...

    jcc 评论0 收藏0
  • leetcode92. Reverse Linked List II

    摘要:题目要求将链表中从第个节点开始翻转至第个节点结束。要求在第一次遍历中即完成该过程。将从第一个该节点开始依次插入最后一个节点后面直到遇到最后一个节点。最后我们还需要一个节点来标记整个链表的起始节点。 题目要求 Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: ...

    luzhuqun 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • [Leetcode] Reverse Linked List 反转链表

    摘要:先跳过前个节点,然后初始化好这五个指针后,用中的方法反转链表。完成了第个节点的反转后,将子链反转前的头节点的设为子链反转过程中的下一个节点,将子链反转前头节点前面一个节点的设为子链反转过程中的当前节点。 Reverse Linked List I Reverse a singly linked list. click to show more hints. Hint: A linke...

    Eminjannn 评论0 收藏0
  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0

发表评论

0条评论

刘永祥

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<