leetcode 剑指offer面试题06,从头到尾打印链表

leetcode 剑指offer面试题06,从头到尾打印链表
题干:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

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

解题思路:
两种方法1.对链表进行反转,然后输出数据
2.先求出链表的长度,然后将数据写入数组中,倒序打印数组。

反转链表的方法:参考(https://blog.csdn.net/qq_42351880/article/details/88637387)

 //反转数组
int* reversePrint(struct ListNode* head, int* returnSize){
    int len = 0;
    struct ListNode* p = head;
    if (head == NULL){
        * returnSize = 0;
        return NULL;
    }
    while (p != NULL){
        len++;
        p = p -> next;
    }
    * returnSize = len;
    int* nums = (int*)malloc(sizeof(int) * len);
    int i = len;
    p = head;       //*****
    while (p != NULL){
        nums[--i] = p -> val;
        p = p -> next;
    }
    return nums;
}
*/


//反转链表
int* reversePrint(struct ListNode* head, int* returnSize){
    if (head == NULL){
        * returnSize = 0;
        return 0;
    }
    int len = 1;
    struct ListNode* tmp;
    struct ListNode* p = head;
    struct ListNode* q = head -> next;
    //struct ListNode* q = NULL;
    while (q != NULL){               //反转链表
        len++;
        tmp = q -> next;
        q -> next = p;
        p = q;
        q = tmp;
    }
    * returnSize = len;                        //存入数组中
    int* nums = (int*)malloc(sizeof(int) * len);
    for (int i = 0; i < len; i++){
        nums[i] = p -> val;
        p = p -> next;
    }
    return nums;
}

你可能感兴趣的:(面试)