LeetCode 206 Reverse Linked List
递归:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head) { if (head == NULL || head->next == NULL) { return head; } struct ListNode* root = reverseList(head->next); head->next->next = head; head->next = NULL; return root; }
迭代:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head) { if (head == NULL || head->next == NULL) { return head; } struct ListNode* root = NULL; while(head) { struct ListNode* temp=head->next; head->next = root; root = head; head = temp; } return root; }