4.写程序将一个单链表翻转。 例如:1->2->3->4->5 翻转后为:5->4->3->2->1.
时间: 2024-05-03 09:20:35 浏览: 139
好的,以下是单链表翻转的程序示例:
```
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;
while (curr != NULL) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
```
使用方法:
```
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);
Solution solution;
ListNode* reversed = solution.reverseList(head);
while (reversed != NULL) {
cout << reversed->val << " ";
reversed = reversed->next;
}
```
输出结果为:
```
5 4 3 2 1
```
阅读全文