题目描述
输入一个链表,反转链表后,输出链表的所有元素。
这个问题十分的简单,但很多人拿到手里偏偏容易写错,今天给大家讲讲怎么理解:
1、初始化参数,前置节点pre,当前节点cur,反转后头节点rhead,下个节点next;
2、循环,把当前节点cur.next指想前驱节点,然后再更换前置、当前节点的值。
然后就结束了。so简单。
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode pre=null;
ListNode cur=head;
ListNode rhead=head;
ListNode next=null;
while(cur!=null){
if(cur.next==null) rhead=cur;
next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return rhead;
}
}