您的位置:首页 > 理论基础

LeetCode-206. Reverse Linked List

2017-04-14 15:04 375 查看
206. Reverse Linked List

Reverse a singly linked list.

用循环的方式:
/**
* 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 *tnow=head, *tnext=head->next, *tone;
head->next=NULL;
while(tnext != NULL){
tone = tnext->next;
tnext->next = tnow;
tnow = tnext;
tnext = tone;
}
return tnow;
}
};

用递归的方式:

class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !(head -> next)) return head;
ListNode* node = reverseList(head -> next);
head -> next -> next = head;
head -> next = NULL;
return node;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  计算机 C++