Reverse a singly linked list.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(!head) return head; ListNode* preHead = head; ListNode* current = preHead->next; ListNode* curNext; head->next = NULL; while(current){ curNext = current->next; current->next = preHead; preHead = current; current = curNext; } return preHead; } };
时间: 2024-10-26 02:26:50