题目:
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?
分析:
分别用迭代和递归来实现。
迭代就是新建一个newhead节点,遍历原链表,将每一个node接到newhead,注意保存head->next用来更新head。
递归则是利用函数先走到链表尾端,依次更新每一个node的next,最后返回newhead。
程序:
//iteratively class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *newhead = NULL; while(head){ ListNode *p = head->next; head->next = newhead; newhead = head; head = p; } return newhead; } };
//recursively class Solution { public: ListNode* reverseList(ListNode* head) { if (head == NULL || head->next == NULL){ return head; } ListNode* newhead = reverseList(head->next); head->next->next = head; head->next = NULL; return newhead; } };
原文地址:https://www.cnblogs.com/silentteller/p/10459455.html
时间: 2024-12-21 21:57:04