问答

leetcode-单链表反转

作者:admin 2021-08-10 我要评论

反转一个单链表。 示例: 输入: 1-2-3-4-5-NULL 输出: 5-4-3-2-1-NULL 力扣的链接如下: 206. 反转链表 我用迭代法写出的代码如下 class Solution { public ListN...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

力扣的链接如下:
206. 反转链表

我用迭代法写出的代码如下

class Solution {

public ListNode reverseList(ListNode head) {
    if(head == null || head.next == null){
        return head;
    }
    ListNode newNode = null;
    while(head != null){
        ListNode tempNode = head;
        tempNode.next = newNode;
        newNode = tempNode;
        head = head.next;
    }
    return newNode;
}

}

请问,问题出在哪里了?
我的思路是遍历原来的链表,然后把每个节点插入一个新的链表,最后返回那个新的链表。

###
tempNode.next = newNode;
head = head.next;

仔细品你的这两句。前一句把head.next置空,后一句又来取next

稍微修改一下:

public ListNode reverseList(ListNode head) {
    if(head == null){
        return head;
    }
    ListNode newNode = null;
    while(head != null){
        ListNode tempNode = newNode;
        newNode = head;
        head = head.next;
        newNode.next = tempNode;
    }
    return newNode;
}

相当于两个相邻指针逐步向右移动,最主要的是要注意指针移动的顺序。先用临时变量tmp记录下左指针的位置,然后移动左指针到右指针位置,然后移动右指针到下一个位置,再把左指针的next志向tmp。

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • leetcode-单链表反转

    leetcode-单链表反转

  • 小程序获取用户输入无法提交至云数据库

    小程序获取用户输入无法提交至云数据库

  • maven连接不上Could not transfer arti

    maven连接不上Could not transfer arti

  • Maven Build Failure | ReasonPhrase:

    Maven Build Failure | ReasonPhrase:

腾讯云代理商
海外云服务器