- 反转链表
1,2,3,4,5
5,4,3,2,1
方法一(迭代法):
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* reverseList (ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while(curr != NULL){
ListNode* nextTemp = curr -> next;
curr -> next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
void printList(ListNode* head){
ListNode* curr = head;
while(curr != nullptr){
cout << curr->val << ',';
curr = curr->next;
}
cout << endl;
}
ListNode* creatList(){
int val;
ListNode* head = nullptr;
ListNode* tail = nullptr;
while(true){
cin >> val;
if(val == -1) break;
ListNode* newNode = new ListNode(val);
if(head == nullptr){
head = newNode;
tail = head;
}
else{
tail->next = newNode;
tail = newNode;
}
}
return head;
}
int main() {
ListNode* head = creatList();
cout << "Original list: ";
printList(head);
ListNode* ReserveListHead = reverseList(head);
printList(ReserveListHead);
return 0;
}
方法二(递归法):
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* reverseList (ListNode* head) {
if(head == nullptr || head->next == nullptr){
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
void printList(ListNode* head){
ListNode* curr = head;
while(curr != nullptr){
cout << curr->val << ' ';
curr = curr->next;
}
cout << endl;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
cout << "Original list: ";
printList(head);
ListNode* ReserveListHead = reverseList(head);
printList(ReserveListHead);
return 0;
}