剑指 Offer 24. 反转链表

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

  示例:

    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL

===============================================================

其实这个就是一个简单的头插法,找到最后一个元素,之后把最后一个元素当作头节点,遍历之前的链表,进行头插,上代码:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (!head)
            return NULL;
        ListNode *end = head;
        while (end->next)
            end = end->next;
        ListNode *h = end;
        while (head != h) {
            ListNode *newNode = head;
            head = head->next;
            newNode->next = end->next;
            end->next = newNode;
        }

        return end;
    }
};有没有大神可以指点一下,请留言

报错信息:

Char 16: runtime error: member access within misaligned address 0xbebebebebebebebe, which requires 8 byte alignment (__ListNodeUtils__.cpp

代码如下:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *end = (ListNode*)malloc(sizeof(ListNode));
        while (head) {
            ListNode *newNode = head;
            head = head->next;
            newNode->next = end->next;
            end->next = newNode;
        }

        return end->next;
    }
};

后来在一篇博客里看到解决办法,现有如下结构体:

struct ListNode {  
    int val;  
    struct ListNode *next;   
};

在申请空间时代码如下:

struct ListNode * temp1=(struct ListNode*)malloc(sizeof(struct ListNode));

由于结构体内存在next指针,而申请结构体空间后同时定义了next指针,此时next指针未指向任何空间,故在测试时可能导致上述错误。

解决方法为:

增加代码使next指针指向空。

temp1->next=NULL;

成功解决,后面看题解中的其他的解法,看到了一个递归,真的牛!!!太简洁了,第一眼我没看懂,后面才揣摩明白,代码如下:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == NULL || head->next == NULL) {
            return head;
        }
        ListNode* ret = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return ret;
    }
};

 

posted on 2022-01-06 22:48  4小旧  阅读(75)  评论(0)    收藏  举报

导航