代码改变世界

NowCoder BM1 反转链表

  jetwill  阅读(24)  评论(0编辑  收藏  举报

描述
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
NowCoder BM1 反转链表

import java.util.*;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null){
            return null;
        }
        ListNode cur = head;
        ListNode pre = null;
        while(cur != null){
            //To record the next node before cutting off the list
            ListNode temp = cur.next;
            //assign pre to current next
            cur.next = pre;
            //assign current to pre
            pre = cur;
            //assign temp to current
            cur = temp;            
        }
        return pre;
    }
}
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2020-08-31 Cannot uninstall 'pyparsing'. It is a distutils installed project
点击右上角即可分享
微信分享提示