可以采用迭代法
new 一个值为null 的新链表,然后new一个临时temp链表,这个temp主要用来head.next 与head之间的替换
首先让head.next指向为null的新链表(反转后head为链表末尾,head的后面为null才对)
然后让新链表指向head, 这样null的上家就变成了head了;这就 从 head→null
最后就是让temp替换head,一次迭代就完成了
/*
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 temp =null;
ListNode newListNode =null;
while(head!=null){
temp=head.next;
head.next=newListNode;
newListNode=head;
head=temp;
}
return newListNode;
}
}