题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null){
return null;
}
int f = 0;
ListNode pre = null;//保存前一节点
ListNode res = null;//最终结果
while(head!=null){
ListNode temp = new ListNode(head.val);//用于保存当前节点的值
res = temp;
if(f==0){
res.next=null;//head的第一个节点,是结果的最后一个节点
}
else {
res.next = pre;
}
pre = res;
f++;
head = head.next;
}
return res;
}
}