用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;
}
void printList(Node *head) {
Node *curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
// create a linked list
Node *head = (Node *) malloc(sizeof(Node));
head->data = 1;
head->next = (Node *) malloc(sizeof(Node));
head->next->data = 2;
head->next->next = (Node *) malloc(sizeof(Node));
head->next->next->data = 3;
head->next->next->next = NULL;
// print the original list
printf("Original list: ");
printList(head);
// reverse the list
head = reverseList(head);
// print the reversed list
printf("Reversed list: ");
printList(head);
return 0;
}
输出:
Original list: 1 2 3
Reversed list: 3 2 1
原文地址: https://www.cveoy.top/t/topic/zF5 著作权归作者所有。请勿转载和采集!