代码改变世界

NowCoder BM1 反转链表

2022-08-31 13:18  jetwill  阅读(22)  评论(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;
    }
}