题目描述:
如果空链表则返回空。
思路:
如果想让一个链表逆序,需要使得节点的指向逆序。对于头节点head,它是反转后的尾节点,所以它的next为null,但在置为null之前,我们需要使用变量记住后续节点,所以cur=head.next。采取头插法,每次从剩余节点链中拿出头节点,将此头节点,以头插法的方式插入已经被拿出的链上。变量cur是用来表示剩余链的头节点,也就是下一个需要反转的节点。cur!=null,代表后续还有节点需要反转,中间变量temp=cur.next为了让cur再次回到剩余链的头节点。cur.next=head以及head=cur,反转节点指向以及让head始终保持在被反转链表的头节点。最后一步cur=temp,使cur重新指向下一个需要被反转的节点。
代码:
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return null;
}
if(head.next==null){
return head;
}
ListNode cur=head.next;
head.next=null;
ListNode temp=null;
while(cur!=null){
temp=cur.next;
cur.next=head;
head=cur;
cur=temp;
}
return head;
}
}