用类C语言设计算法实现循环单链表就地逆置
时间: 2023-05-25 09:04:10 浏览: 147
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
void init(Node** head, int n) {
*head = (Node*)malloc(sizeof(Node));
(*head)->data = 1;
(*head)->next = NULL;
Node* ptr = *head;
for (int i = 2; i <= n; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = i;
newNode->next = NULL;
ptr->next = newNode;
ptr = ptr->next;
}
ptr->next = *head; // 链接成循环链表
}
void printList(Node* head) {
Node* ptr = head;
do {
printf("%d ", ptr->data);
ptr = ptr->next;
} while (ptr != head);
}
void reverseList(Node** head) {
if (*head == NULL || (*head)->next == NULL) {
return;
}
Node* prev = NULL;
Node* cur = *head;
Node* nxt = (*head)->next;
do {
cur->next = prev;
prev = cur;
cur = nxt;
nxt = nxt->next;
} while (cur != *head);
(*head)->next = prev;
*head = prev;
}
int main() {
Node* head = NULL;
int n = 5;
init(&head, n);
printf("原始链表数据:\n");
printList(head);
reverseList(&head);
printf("\n逆置后的链表数据:\n");
printList(head);
return 0;
}备注:此算法实现了循环单链表的就地逆置,可供参考。
阅读全文