NowCoder BM1 反转链表
作者:互联网
描述
给定一个单链表的头结点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;
}
}
标签:pre,ListNode,cur,val,next,链表,BM1,NowCoder,null 来源: https://www.cnblogs.com/chenjo/p/16642765.html