标签:
题意:把一个链表倒过来。
题解:有递归和非递归两种方式,主要就是考察指针操作的熟悉程度。
递归的方法:
/** * 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||!(head->next))return head; ListNode* p=reverseList(head->next); head->next->next=head; head->next=nullptr; return p; } };
非递归:就一个一个转过来方向就好了。转的时候需要用两个辅助指针,一个指向该节点的前一个节点,一个指向后一个节点。
/** * 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||!(head->next))return head; ListNode* pre=nullptr; ListNode* back=head->next; while(back){ head->next=pre; pre=head; head=back; back=back->next; } head->next=pre; return head; } };
leetcode 206. Reverse Linked List
标签:
原文地址:http://www.cnblogs.com/zywscq/p/5429141.html