给你单链表的头节点?head ?,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
输入:head = []
输出:[]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reverse-linked-list/
/**
* 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)
{
ListNode prior = null;
ListNode cur = head;
while (cur != null) //同时解决链表为空的情况
{
ListNode temp = cur.next; //暂存下个结点的值为之后cur指针赋值
cur.next = prior; //next指向之前的节点,即反转
prior = cur; //先前指针后移
cur = temp; //当前指针后移
}
return prior;
}
}
|