题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
思路:从前到后拿节点,循环将新节点作为头结点链接到新链表中
/*
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 newHead = head;
ListNode p;
while(head!=null){
p = head;
head = head.next;
p.next = newHead;
p.next = null;
if(p!=newHead){
p.next = newHead;
newHead = p;
}
}
return newHead;
}
}