设计算法实现将单链表中数据逆置的操作
时间: 2023-05-21 11:05:27 浏览: 119
可以使用迭代或递归方式来实现将单链表逆置的操作。以下是递归实现的示例代码:
```
void ReverseList(Node* node, Node* &head) {
if (node == nullptr) return;
if (node->next == nullptr) {
head = node;
return;
}
ReverseList(node->next, head);
node->next->next = node;
node->next = nullptr;
}
```
其中,Node 表示单链表中的节点,head 表示单链表的头节点。在递归调用的过程中,我们令 head 指向逆置后的链表的头节点(即原链表的尾节点)。
相关问题
设计算法实现将单链表中数据逆置的操作。用C语言代码
好的,我可以为您提供一个C语言的单链表逆置的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node* reverseList(Node *head) {
Node *prev = NULL;
Node *curr = head;
Node *next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
// create linked list 1-2-3-4-5
Node *head = (Node*)malloc(sizeof(Node));
head->data = 1;
Node *node2 = (Node*)malloc(sizeof(Node));
node2->data = 2;
head->next = node2;
Node *node3 = (Node*)malloc(sizeof(Node));
node3->data = 3;
node2->next = node3;
Node *node4 = (Node*)malloc(sizeof(Node));
node4->data = 4;
node3->next = node4;
Node *node5 = (Node*)malloc(sizeof(Node));
node5->data = 5;
node4->next = node5;
node5->next = NULL;
// reverse the linked list
head = reverseList(head);
// print the reversed linked list
Node *temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
// free the memory used by the linked list
temp = head;
while (temp != NULL) {
Node *temp2 = temp->next;
free(temp);
temp = temp2;
}
return 0;
}
```
这个代码使用了迭代法实现单链表的逆置。具体来说,在逆置过程中,我们使用三个指针,分别为`prev`、`curr`和`next`,初始值分别为`NULL`、头结点和头结点的下一个节点。通过循环遍历单链表,依次将当前节点的下一个节点指向前一个节点,然后将三个指针后移一位。最终,逆置完成后,我们将头结点指向新的逆置后的链表的头结点(也就是原先链表的尾节点),并返回该头结点。
设计算法实现将单链表中数据逆置后输出。用C语言代码
如下所示:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点结构体
struct node {
int data;
struct node *next;
};
// 定义单链表逆置函数
struct node* reverse(struct node *head) {
struct node *prev = NULL;
struct node *curr = head;
struct node *next;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// 定义单链表输出函数
void print_list(struct node *head) {
struct node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
// 定义单链表 head 节点并初始化
struct node *head = (struct node*)malloc(sizeof(struct node));
head->data = 1;
// 定义单链表节点 a, b, c 并初始化
struct node *a = (struct node*)malloc(sizeof(struct node));
a->data = 2;
struct node *b = (struct node*)malloc(sizeof(struct node));
b->data = 3;
struct node *c = (struct node*)malloc(sizeof(struct node));
c->data = 4;
// 手动建立单链表
head->next = a;
a->next = b;
b->next = c;
c->next = NULL;
printf("反转前:\n");
print_list(head);
// 调用单链表反转函数
head = reverse(head);
printf("反转后:\n");
print_list(head);
return 0;
}
```
输出:
```
反转前:
1 2 3 4
反转后:
4 3 2 1
```
阅读全文