https://blog.csdn.net/FX677588/article/details/72357389
上面这篇博客的图解很清晰,看不懂代码可以看这里
第一种方法:迭代
head表示当前节点,pre是head的前一个节点,next是head的后一个节点。
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null) return null;
ListNode pre =null;
ListNode next=null;
while(head!=null){
next=head.next;//一定要先把next节点保存,不然链表会断开
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}
第二种方法:递归
先遍历到表尾,再改变指针方向。
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode pre=ReverseList(head.next);
head.next.next=head;
head.next=null;//防止链表形成环
return pre;
}
}