c++写一段带头结点的单链表创建程序
时间: 2024-06-06 09:07:21 浏览: 82
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node)); // 创建头结点
head->next = NULL;
Node* tail = head;
int x;
printf("请输入链表中的元素,以-1结束:\n");
while (scanf("%d", &x) && x != -1) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = x;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
}
return head;
}
void printList(Node* head) {
printf("链表中的元素为:");
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node* head = createList();
printList(head);
return 0;
}
阅读全文