LeetCode OJ 之 Reverse Linked List (链表逆序)

来源:互联网 发布:剑灵灵剑捏脸数据导入 编辑:程序博客网 时间:2024/06/05 15:40

题目:

Reverse a singly linked list.

click to show more hints.

思路:

1、迭代

2、递归

迭代代码:

/** * 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 *p1 = head , *p2 = head->next;        p1->next = NULL;        while(p2)        {            ListNode *tmp = p2->next;            p2->next = p1;            p1 = p2;            p2 = tmp;        }        return p1;    }};

递归代码:

/** * 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 *newhead = reverseList(p);        p->next = head;        return newhead;    }};



0 0
原创粉丝点击