定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
题解:见注释
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode res = head;
int len = 0, i = 0;
//计算链表长度
while(res != null){
res = res.next;
len++;
}
//创建和链表长度相同的数组
int[] a = new int[len];
int len1 = len - 1;
res = head;
//将链表值存入数组
while(res != null){
a[i++] = res.val;
res = res.next;
}
res = head;
//将数组值逆序值存入链表中
while(res != null){
res.val = a[len1--];
res = res.next;
}
return head;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof