链表_LeetCode_206_反转链表

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

法一:反向初始化

struct ListNode* reverseList(struct ListNode* head){
    struct ListNode* L=NULL;
    while(head){
        struct ListNode* p=(struct ListNode*)malloc(sizeof(struct ListNode));
        p->val=head->val;
        p->next=L;
        L=p;
        head=head->next;
    }
    return L;
}

法二:双指针

(1)

    struct ListNode* reverseList(struct ListNode* head) {
        struct ListNode* cur = NULL, *pre = head;
        while (pre != NULL) {
            struct ListNode* t = pre->next;
            pre->next = cur;
            cur = pre;
            pre = t;
        }
        return cur;
    }

(2)

    struct ListNode* reverseList(struct ListNode* head) {
        if (head == NULL) { return NULL; }
        struct ListNode* cur = head;
        while (head->next != NULL) {
            struct ListNode* t = head->next->next;
            head->next->next = cur;
            cur = head->next;
            head->next = t;
        }
        return cur;
    }

法三:递归

    struct ListNode* reverseList(struct ListNode* head) {
        if (head == NULL || head->next == NULL) {
            return head;
        }
        struct ListNode* ret = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return ret;
    }

 

posted @ 2020-03-26 12:41  Ruanzy  阅读(130)  评论(0)    收藏  举报