206. Reverse Linked List
题意:将链表转置
我的思路:递归实现,1A
我的代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverse(ListNode* head) { ListNode* ret = head; if (head->next) { ret = reverse(head->next); head->next->next = head; } return ret; } ListNode* reverseList(ListNode* head) { if (head == NULL) return head; ListNode* ans, *tmp = head; ans = reverse(head); tmp->next = NULL; return ans; } };
九章最优解:循环实现,被秒成了渣T T
class Solution { public: /** * @param head: The first node of linked list. * @return: The new head of reversed linked list. */ ListNode *reverse(ListNode *head) { ListNode *prev = NULL; while (head != NULL) { ListNode *temp = head->next; head->next = prev; prev = head; head = temp; } return prev; } };
时间: 2024-10-08 02:42:04