【代码】
/** * 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 res = head;
ListNode head1 = head; //用来算链表长度
int len = 0;
while (head1 != null) //用来算链表长度
{
len++;
head1 = head1.next;
}
int[] arr = new int[len]; //先将每个节点的值保存起来
head1 = head;
for (int i = 0; i < len; i++)
{
arr[i] = head1.val;
head1 = head1.next;
}
head1 = head; //逆序赋值
for (int i = len - 1; i >= 0; i--)
{
head1.val = arr[i];
head1 = head1.next;
}
return res;
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/qq_38689263/article/details/120383939
内容来源于网络,如有侵权,请联系作者删除!