首页 > 其他分享 >力扣_剑指Offer_个人题解

力扣_剑指Offer_个人题解

时间:2022-10-19 22:11:05浏览次数:99  
标签:链表 head ListNode Offer int 题解 arr next 力扣

day02

剑指 Offer 06. 从尾到头打印链表

题目描述:

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

限制:

0 <= 链表长度 <= 10000

题解:

/**  * Definition for singly-linked list.  * public class ListNode {  *     int val;  *     ListNode next;  *     ListNode(int x) { val = x; }  * }  */ class Solution {     int[]arr=new int[10000];     int[]arr1;     int i=0,count=0,k=0;     public int[] reversePrint(ListNode head) {         while(head!=null){             arr[i++]=head.val;             count++;             head=head.next;         }         arr1=new int[count];         for(int j=count-1;j>=0;j--){             arr1[k++]=arr[j];         }         return arr1;     } }

 

剑指 Offer 24. 反转链表

 

题目描述:

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

 

示例:

 

输入: 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 {     ListNode l=null;     ListNode ll=null;     int i=0;     int[]arr=new int[5000];     public ListNode reverseList(ListNode head) {         while(head!=null){             //temp=head;             arr[i++]=head.val;             //System.out.println(arr[i]);             head=head.next;             //head.next=temp;         }         //System.out.println(i);         for(int j=i-1;j>=0;j--){             if(l==null){                 l=new ListNode(arr[j]);                 ll=l;             }             else{                 ll.next=new ListNode(arr[j]);                 ll=ll.next;             }         }         return l;     } }

 

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/fan-zhuan-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 

标签:链表,head,ListNode,Offer,int,题解,arr,next,力扣
From: https://www.cnblogs.com/hngz/p/16808049.html

相关文章