reverse a linked-list(C++)

#include<iostream>
using namespace std;
class Node
{
public:
Node(int value) : value(value), next(NULL) {}
public:
int value;
Node* next;
};
Node* reverseList(Node* head)
{
Node* newList = NULL;
Node* current = head;
while (current)
{
Node* next = current->next;
current->next = newList;
newList = current;
current = next;
}
return newList;
}
void printList(Node* head);
void listTests()
{
Node* one = new Node(1);
Node* two = new Node(2);
Node* three = new Node(3);
Node* four = new Node(4);
Node* five = new Node(5);
one->next = two;
two->next = three;
three->next = four;
four->next = five;
Node* head = one;
printList(head);
head = reverseList(head);
printList(head);
head = reverseList(head);
printList(head);
// cleanup memory
Node* current = head;
while (current)
{
Node* next = current->next;
delete current;
current = next;
}
}
void printList(Node* head)
{
Node* current = head;
while (current)
{
cout << current->value;
current = current->next;
}
cout << endl;
}

int main(){
listTests();
return 0;
}

转载于:https://www.cnblogs.com/strong-jeffrey/p/3809514.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
链表翻转是链表操作中的一项基本操作,可以将链表中的节点按照相反的顺序排列。C语言中可以使用指针来实现链表的翻转。 下面是一个简单的链表翻转的例子: ```c #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node* next; } Node; Node* reverseList(Node* head) { if (head == NULL || head->next == NULL) { return head; } Node* p = reverseList(head->next); head->next->next = head; head->next = NULL; return p; } void printList(Node* head) { Node* p = head; while (p != NULL) { printf("%d ", p->data); p = p->next; } printf("\n"); } int main() { Node* head = (Node*)malloc(sizeof(Node)); head->data = 1; Node* p1 = (Node*)malloc(sizeof(Node)); p1->data = 2; head->next = p1; Node* p2 = (Node*)malloc(sizeof(Node)); p2->data = 3; p1->next = p2; p2->next = NULL; printf("原链表:"); printList(head); Node* newHead = reverseList(head); printf("翻转后的链表:"); printList(newHead); return 0; } ``` 在上面的代码中,我们定义了一个包含数据和下一个节点指针的结构体Node,然后我们定义了一个reverseList函数,该函数使用递归来翻转链表。在翻转链表的过程中,我们首先递归遍历链表,然后将当前节点的下一个节点的next指针指向当前节点,最后将当前节点的next指针设为NULL,以防止链表出现环。最后返回递归遍历的第一个节点,也就是翻转后的链表的头节点。 最后在main函数中,我们创建了一个包含3个节点的链表,然后打印出原链表和翻转后的链表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值