Reverse a singly linked list.
A linked list can be reversed either iteratively or recursively. Could you implement both?
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <iostream> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* Pre = NULL; ListNode* Now = head; ListNode* Next = NULL; while(Now) { Next = Now->next; Now->next = Pre; Pre = Now; Now = Next; } return Pre; } };
原文地址:http://blog.csdn.net/sheng_ai/article/details/45815155