c语言中实现带头节点单链表的逆置的代码是什么样的
时间: 2023-03-27 20:02:05 浏览: 122
以下是实现带头节点单链表逆置的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node* createList(int n) {
Node *head = (Node*)malloc(sizeof(Node));
head->next = NULL;
Node *tail = head;
for (int i = ; i < n; i++) {
Node *node = (Node*)malloc(sizeof(Node));
scanf("%d", &node->data);
node->next = NULL;
tail->next = node;
tail = node;
}
return head;
}
void printList(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void reverseList(Node *head) {
Node *p = head->next;
Node *q = NULL;
head->next = NULL;
while (p != NULL) {
q = p->next;
p->next = head->next;
head->next = p;
p = q;
}
}
int main() {
int n;
scanf("%d", &n);
Node *head = createList(n);
printList(head);
reverseList(head);
printList(head);
return ;
}
```
以上代码实现了带头节点单链表的逆置,具体实现方法是通过遍历链表,将每个节点的 next 指针指向其前驱节点,最后将头节点的 next 指针指向原链表的尾节点。
阅读全文
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)