C++示例:
/**
* 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 == NULL) {
cout << "The list is empty." << endl;
return NULL;
}
if (head->next == NULL) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
// 迭代实现反转
/*ListNode* reverseList(ListNode* head) {
if (head == NULL) {
cout << "The list is empty." << endl;
return NULL;
}
if (head->next == NULL) {
return head;
}
ListNode* p = head;
ListNode* pPrev = NULL;
while (p != NULL) {
ListNode* temp = p->next;
p->next = pPrev;
pPrev = p;
p = temp;
}
return pPrev;
}*/
};
原文地址:https://www.cnblogs.com/yiluyisha/p/9266093.html
时间: 2024-11-06 09:51:34