建立一个带头结点的单链表,结点的值域为整形数据。要求按用户输入的数据建立相应单链表在线等

2025-04-07 03:18:53
推荐回答(2个)
回答1:

下面是你要的链表:

#include
#include
struct Node {
int value;
Node * next;
};
Node * buildList(int arr[], int n)
{
if(n == 0) return NULL;
Node * head = new Node();
head->value = arr[0];
head->next = NULL;
Node *p = head, *q;
for(int i=1; i q = new Node();
q->value = arr[i];
q->next = NULL;
p->next = q;
p = p->next;
}
return head;
}
void printList(Node *head)
{
Node *p = head;
while(p!=NULL) {
printf("%d ", p->value);
p = p->next;
}
printf("\n");
}
int main()
{
int n , a[100];
printf("输入节点的个数:");
scanf("%d", &n);
printf("输入节点的值:");
for(int i=0; i scanf("%d", &a[i]);
Node * list = buildList(a, n);
printList(list);
//float x;
//scanf("%f", &x);
}

回答2:

#include
#include

typedef int ElemType;

typedef struct node {
int data;
struct node *prior,*next;
} *SqList;

SqList CreateList(int n) { // 创建单向循环链表
SqList head,p,q;
head = p = (SqList)malloc(sizeof(node));
for(int i = 0;i < n;i++) {
q = (SqList)malloc(sizeof(node));
q->data = 2*i + 1;
p->next = q;
p = q;
}
p->next = head;
return head;
}

void PrintList(SqList head) {
SqList p = head->next;
while(p != head) {
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}