206. Reverse Linked List

来源:互联网 发布:串口收到的数据都是0 编辑:程序博客网 时间:2024/06/15 22:08

Reverse a singly linked list.

递归与指针实现代码贴上

#include <cstdlib> struct ListNode {     int val;     ListNode *next;    ListNode(int x) : val(x), next(NULL) {}  };class Solution {public:ListNode* reverseList(ListNode* head) {/*if ((!head) || (!head->next))return head;ListNode* ptr = head->next;ListNode* p = head;p->next = NULL;ListNode* cur = NULL;while (ptr){cur = ptr->next;ptr->next = p;p = ptr;ptr = cur;}return p;*/if ((!head) || (!head->next))return head;ListNode* ptr = head->next;ListNode* p = reverseList(ptr);head->next = NULL;ptr->next = head;return p;}};

0 0
原创粉丝点击