LeetCode:Reverse LinkedList
problem:
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
solution:头插法逆转链表
/** * 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 result(-1); ListNode *cur=head; while(cur!=NULL) { ListNode *nnode=new ListNode(cur->val); nnode->next=result.next; result.next=nnode; cur=cur->next; } return result.next; } };