Reverse Linked List

来源:互联网 发布:单片机程序员招聘 编辑:程序博客网 时间:2024/06/06 03:16

 

Reverse a singly linked list.

单链表的逆序有两种方法,一种是递归的,另一种是非递归的(头插法)。

递归解法如下,耗时11ms:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseList(ListNode* head) {        if(head == NULL || head->next == NULL)            return head;        ListNode* p = reverseList(head->next);        head->next->next = head;        head->next = NULL;        return p;    }};


递归解法如下,耗时8ms:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseList(ListNode* head) {        if(head == NULL || head->next == NULL)            return head;        ListNode* p = head->next;        head->next = NULL;        ListNode* q;        while(p) {            q = p;            p = p->next;            q->next = head;            head = q;        }        return head;    }};


 

0 0