原题:
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULLFollow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
有两种逆置方法,一种用的比较多是首插循环的方式,即设置一个头节点head2,使head2->next=nullptr,然后一直按首插法插入,例如:(h) (1->2->3->4) ==> (h->1) (2->3->4) ==>(h->2->1) (3->4)...
结果:
Success
Runtime: 4 ms, faster than 99.70% of C++ online submissions forReverse Linked List.
Memory Usage: 9.1 MB, less than 59.47% of C++ online submissions for Reverse Linked List.
代码:
/**
* Definition for singly-linked list.
* struct ListNode