Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:

image
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:

image
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
- The number of nodes in the list is the range
[0, 5000]. -5000 <= Node.val <= 5000
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
听说反转链表是算法中最最最基础的, 我写了半天写不出来,感觉都要自闭了.
一开始我希望递归结束后自动将前一个结点的值作为函数的返回值 return 回去,但是我忽略了, 使用递归返回的话,那么就是下一层的前一个结点,返回到上一层, 每个节点都自成环了,不能正确的将整个链表反转过来.
那么只能在递归结束之后,在本层中使用前一个结点值作为 next 指针的新值.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void resurse(struct ListNode* node, struct ListNode *pre , struct ListNode** newHead){
if (node->next != NULL) {
resurse(node->next, node, newHead);
}
else {
*newHead = node;
}
node->next = pre;
}
struct ListNode* reverseList(struct ListNode* head){
if(head == NULL) return NULL;
struct ListNode* newHead;
resurse(head, NULL, &newHead);
return newHead;
}
迭代版本
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode *tmp = head;
struct ListNode *pre = NULL;
struct ListNode *next = NULL;
while( tmp != NULL){
if( tmp->next == NULL ) head = tmp;
next = tmp->next;
tmp->next = pre;
pre = tmp;
tmp = next;
}
return head;
}