LeetCode-206. Reverse Linked List

来源:互联网 发布:域名检测接口 编辑:程序博客网 时间:2024/06/04 18:29

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;     }}; 


0 0
原创粉丝点击