用c语言实现单链表的逆置
时间: 2023-08-31 19:09:55 浏览: 94
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node* next;
}Node;
Node* createList(int n);
void printList(Node* head);
Node* reverseList(Node* head);
int main()
{
int n;
printf("Enter the number of nodes:");
scanf("%d", &n);
Node* head = createList(n);
printf("Original list:\n");
printList(head);
head = reverseList(head);
printf("Reversed list:\n");
printList(head);
return 0;
}
Node* createList(int n)
{
Node* head = NULL;
Node* tail = NULL;
for(int i=0; i<n; i++)
{
Node* newNode = (Node*)malloc(sizeof(Node));
printf("Enter the data of node %d: ", i+1);
scanf("%d", &newNode->data);
newNode->next = NULL;
if(head == NULL)
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
}
return head;
}
void printList(Node* head)
{
Node* p = head;
while(p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
Node* reverseList(Node* head)
{
Node* prev = NULL;
Node* curr = head;
Node* next;
while(curr != NULL)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
```
阅读全文