版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zztingfeng/article/details/82287708
题目:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
分析:此题为链表的常规题,步骤概括为:备份head->next;修改head->next;移动head与new_head;
c++代码:
#include <stdio.h>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *new_head = NULL;
while(head)
{
ListNode *next = head->next;
head->next = new_head;
new_head=head;
head=next;
}
return new_head;
}
};
int main()
{
ListNode a(1);
ListNode b(2);
ListNode c(3);
ListNode d(4);
ListNode e(5);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
e.next = NULL;
Solution s;
ListNode *head=&a;
printf("反转前链表:\n");
while(head)
{
printf("%d\n",head->val);
head = head->next;
}
head=s.reverseList(&a);
printf("反转后链表:\n");
while(head)
{
printf("%d\n",head->val);
head = head->next;
}
}