用C语言实现从键盘依次输入正整数,利用尾插法形成单链表依次输出,再将输入的数据逆序建立单链表并输出。
时间: 2024-02-13 11:02:30 浏览: 93
好的,我可以回答这个问题。
以下是用C语言实现从键盘输入正整数,利用尾插法形成单链表并输出的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表的结构体
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
// 尾插法建立单链表
ListNode* createList() {
ListNode *head = NULL, *tail = NULL;
int num;
while (scanf("%d", &num) == 1 && num > 0) {
ListNode *node = (ListNode*) malloc(sizeof(ListNode));
node->val = num;
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 输出单链表
void printList(ListNode* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
// 读入数据并建立单链表
printf("Please input integers separated by spaces, end with a non-positive integer:\n");
ListNode *head = createList();
// 输出单链表
printf("The linked list is:\n");
printList(head);
return 0;
}
```
接下来是将输入的数据逆序建立单链表并输出的代码:
```c
// 将单链表逆序
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode *prev = NULL, *cur = head, *next = head->next;
while (cur != NULL) {
cur->next = prev;
prev = cur;
cur = next;
if (next != NULL) {
next = next->next;
}
}
return prev;
}
int main() {
// 读入数据并建立单链表
printf("Please input integers separated by spaces, end with a non-positive integer:\n");
ListNode *head = createList();
// 输出单链表
printf("The linked list is:\n");
printList(head);
// 将单链表逆序
head = reverseList(head);
// 输出逆序后的单链表
printf("The reversed linked list is:\n");
printList(head);
return 0;
}
```
希望这个回答能够帮到你!
阅读全文