Leetcode 206. Reverse Linked List (Easy) (cpp)

来源:互联网 发布:java swing 表格 编辑:程序博客网 时间:2024/04/29 05:08

Leetcode 206. Reverse Linked List (Easy) (cpp)

Tag: Linked List

Difficulty: Easy


/*206. Reverse Linked List (Easy)Reverse a singly linked list.click to show more hints.Hint:A linked list can be reversed either iteratively or recursively. Could you implement both?*//** * 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, *prev = NULL;        while (head != NULL) {            ListNode *post = head -> next;            head -> next = prev;            prev = head;            head = post;        }        return prev;    }};class Solution {public:    ListNode* reverseList(ListNode* head) {        if (head == NULL || head -> next == NULL) {            return head;        }        ListNode *newhead = reverseList(head -> next);        head -> next -> next = head;        head -> next = NULL;        return newhead;    }};


0 0
原创粉丝点击