Reverse a singly linked list.
分别用迭代和递归实现
struct ListNode { int val; struct ListNode *next; };
迭代实现:
struct ListNode* reverseList(struct ListNode* head) { struct ListNode *pre = NULL; struct ListNode *cur = head; while( cur != NULL ) { struct ListNode *after = cur->next; cur->next = pre; pre = cur; cur = after; } return pre; }
递归实现:
1)如果head为空,或者只有head这一个节点,return head即可;
2)先遍历head->next为首的链表,得到一个头结点newHead;
3)把head赋值给head->next->next, head->next为空;
4)返回newHead。
struct ListNode* reverseList(struct ListNode* head) { if(head == NULL || head->next == NULL) return head; struct ListNode* newHead = reverseList(head->next); head->next->next = head; head->next = NULL; return newHead; }