LC 反转链表

x33g5p2x  于2021-09-19 转载在 其他  
字(0.6k)|赞(0)|评价(0)|浏览(326)

LC 反转链表


  • 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表

【代码】

/** * 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;
    }
}

相关文章