c语言线性表怎么循环赋值
时间: 2024-03-07 13:20:58 浏览: 84
C语言的线性表的操作
对于循环线性表的赋值,可以使用for循环来实现。以单向循环链表为例,代码如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node * next;
} Node, *List;
List createList(int n) {
if(n < 1) return NULL;
List head, p;
head = (List) malloc(sizeof(Node));
head->next = NULL;
p = head;
for(int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
List temp = (List) malloc(sizeof(Node));
temp->data = x;
temp->next = head;
p->next = temp;
p = temp;
}
return head;
}
void printList(List head) {
if(head == NULL) return;
List p = head->next;
while(p != head) {
printf("%d ", p->data);
p = p->next;
}
}
void assign(List head, int value) {
if(head == NULL) return;
List p = head->next;
while(p != head) {
p->data = value;
p = p->next;
}
}
int main() {
int n;
printf("请输入线性表的元素个数:\n");
scanf("%d", &n);
List head = createList(n);
printf("原始线性表:\n");
printList(head);
printf("\n请输入要赋的值:\n");
int value;
scanf("%d", &value);
assign(head, value);
printf("赋完值后的线性表:\n");
printList(head);
printf("\n");
return 0;
}
```
这个程序的功能就是循环赋值,将单向循环链表的每个节点的值都赋成同一个数值。
阅读全文