设计一个c语言算法,将单链表中结点以逆序排列。逆序的单链表中的结点均为原表中的结点。
时间: 2023-05-13 12:05:26 浏览: 97
以下是一个C语言算法,可以将单链表中的结点以逆序排列:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void reverseList(struct Node** head) {
struct Node* prev = NULL;
struct Node* current = *head;
struct Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
void printList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
}
int main() {
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printf("Original List: ");
printList(head);
reverseList(&head);
printf("\nReversed List: ");
printList(head);
return 0;
}
```
这个算法会将单链表中的结点以逆序排列,并且逆序的单链表中的结点均为原表中的结点。
阅读全文