单链表翻转
本文最后更新于:Wednesday, August 5th 2020, 6:20 pm
单链表翻转
解法一、拆卸+拼接
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| struct ListNode *reverseList(struct ListNode* head){ struct ListNOde *newHead = NUll; struct ListNode *node = NULL; while (head != NULL) { node = head; head = head->next;
node->next = newHead; newHead = node; } return newHead; }
|

解法二、三指针法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| struct ListNode *reverseList(struct ListNode* head) { if (head == NULL) { return NULL; } struct ListNode *p0 = NULL; struct ListNode *p1 = head; struct ListNode *p2 = head->next; while (p1 != NULL) { p1->next = p0;
p0 = p1; p1 = p2; if (p2 != NULL) { p2 = p2->next; } } return p0; }
|

参考博客