给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
输入:head = [1,2] 输出:[2,1]
输入:head = [ ] 输出:[ ]
[0,500]
-5000 <= Node.val <= 5000
head
置为null
cur
和curNext
,cur
指向头结点的next
,表示要反转的元素;curNext
指向cur
的next
,表示要反转元素的下一个元素
/**
* Definition for singly-linked list.
* 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 head;
}
if (head.next == null) { // 链表里只有一个元素
return head;
}
ListNode cur = head.next; // 要反转的元素
head.next = null;
while (cur != null) {
ListNode curNext = cur.next;
// 头插法
cur.next = head;
head = cur;
cur = curNext;
}
return head;
}
}
运行结果: