不带头节点的单链表原地逆置C语言实现
时间: 2023-11-19 14:00:17 浏览: 78
```c
#include<stdio.h>
#include<stdlib.h>
typedef struct Node {
int data;
struct Node* next;
}Node;
Node* createList(int n) {
Node* head = NULL;
Node* tail = NULL;
for (int i = 0; i < n; i++) {
Node* node = (Node*)malloc(sizeof(Node));
scanf_s("%d", &node->data);
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
}
else {
tail->next = node;
tail = node;
}
}
return head;
}
Node* reverseList(Node* head) {
Node* cur = head;
Node* pre = NULL;
while (cur) {
Node* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
void printList(Node* head) {
Node* cur = head;
while (cur) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
int main() {
int n;
scanf_s("%d", &n);
Node* head = createList(n);
printList(head);
head = reverseList(head);
printList(head);
return 0;
}
```
阅读全文