用c++写单向链表的逆置
时间: 2023-05-31 14:03:00 浏览: 102
以下是用C语言实现单向链表逆置的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node *createList(int n) {
Node *head, *p, *q;
int i;
head = (Node*) malloc(sizeof(Node));
head->next = NULL;
q = head;
for (i = 0; i < n; i++) {
p = (Node*) malloc(sizeof(Node));
scanf("%d", &p->data);
p->next = NULL;
q->next = p;
q = p;
}
return head;
}
void printList(Node *head) {
Node *p;
p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
Node *reverseList(Node *head) {
Node *p, *q, *r;
if (head == NULL || head->next == NULL) {
return head;
}
p = head->next;
q = p->next;
while (q != NULL) {
r = q->next;
q->next = p;
p = q;
q = r;
}
head->next->next = NULL;
head->next = p;
return head;
}
int main() {
int n;
Node *head;
scanf("%d", &n);
head = createList(n);
printf("Original list: ");
printList(head);
head = reverseList(head);
printf("Reversed list: ");
printList(head);
return 0;
}
```
代码中的 `createList()` 函数用于创建单向链表, `printList()` 函数用于输出单向链表, `reverseList()` 函数用于将单向链表逆置。在 `reverseList()` 函数中,使用三个指针 `p`、 `q` 和 `r` 分别表示当前节点、下一个节点和下下个节点,通过不断修改节点指针的指向,实现单向链表的逆置。
阅读全文