|
23鱼币
- struct SUN
- {
- int num;
- struct SUN* next;
- };
- void Pint(struct SUN* head)
- {
- struct SUN* temp;
- temp = head;
-
- while (temp != NULL)
- {
- printf("%d", temp->num);
- temp = temp->next;
- }
- }
- void add(struct SUN** head, int num)
- {
- struct SUN* space, * temp;
- space = (struct SUN*)malloc(sizeof(struct SUN));
- space->num = num;
- temp = *head;
- *head = space;
- space->next = temp;
-
- if (space->next != NULL)
- {
- printf("空间满了\n");
- }
- else
- {
- space->next = *head;
- }
- }
- int main()
- {
- int num;
- struct SUN* head = NULL;//链头
- printf("input num:");
- scanf("%d", &num);
- for (int i = 0; i < num; i++)
- {
- add(&head, i);
- }
- Pint(head);//若循环num ~ 0 则成功连接
-
- return 0;
- }
复制代码
本帖最后由 傻眼貓咪 于 2022-5-23 17:43 编辑
我的思路:
第一次赋值:
头指针赋值后,next 指向自己便可。
接下来的赋值:
赋值函数,先传入头指针
头指针 -> 指针 A -> ............ -> 尾指针 -> 头指针
设新指针 p,将值赋值于 p
将 p 指向头指针->next(如上,也就是指针 A)
将头指针->next 指向 p
示例:头指针 -> p -> 指针 A -> ............ -> 尾指针 -> 头指针
- #include <stdio.h>
- #include <malloc.h>
- typedef struct Node {
- int data;
- struct Node* next;
- }LinkedList;
- void insert(LinkedList** head, int data) {
- if (!(*head)) {
- (*head) = (LinkedList*)malloc(sizeof(LinkedList));
- if (*head) {
- (*head)->data = data;
- (*head)->next = (*head);
- }
- }
- else {
- LinkedList* p = (LinkedList*)malloc(sizeof(LinkedList));
- if (p) {
- p->data = data;
- p->next = (*head)->next;
- (*head)->next = p;
- }
- }
- }
- void freeAll(LinkedList** head) {
- LinkedList* p, * q = (*head);
- if (*head) {
- p = (*head);
- (*head) = (*head)->next;
- free(p);
- }while (q != head);
- free(head);
- }
- void print(LinkedList* head) {
- LinkedList* p = head;
- if (head) {
- do {
- head = head->next;
- printf("%d ", head->data);
- } while (p != head);
- }
- }
- int main(void) {
- int arr[] = { 7, 14, 21, 28, 35 };
- LinkedList* head = NULL;
- for (int i = 0; i < 5; ++i) {
- insert(&head, arr[i]);
- }
- print(head);
- freeAll(&head);
- return 0;
- }
复制代码
|
最佳答案
查看完整内容
我的思路:
第一次赋值:
头指针赋值后,next 指向自己便可。
接下来的赋值:
赋值函数,先传入头指针
头指针 -> 指针 A -> ............ -> 尾指针 -> 头指针
设新指针 p,将值赋值于 p
将 p 指向头指针->next(如上,也就是指针 A)
将头指针->next 指向 p
示例:头指针 -> p -> 指针 A -> ............ -> 尾指针 -> 头指针
|