206、Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
思路
经典的链表逆序问题,题目要求两种方式实现:迭代和非迭代
c++11
非递归方法
定义一个新的头指针为空,之后遍历原链表,将head插入到new_head前面,同时更新new_head
/**
* 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) {
ListNode* new_head = NULL;
while (head) {
ListNode* tmp = head->next;
head->next = new_head;
new_head = head;
head = tmp;
}
return new_head;
}
};
ac结果:
Runtime: 8 ms, faster than 100.00% of C++ online submissions for Reverse Linked List.
Memory Usage: 9.3 MB, less than 19.73% of C++ online submissions for Reverse Linked List.