在头文件中:
struct myStruct{
int data;
struct myStruct *next;
};
typedef struct myStruct myStruct;
相对函数:
myStruct * create(){
myStruct * a = NULL;
int size;
printf("Enter Size of List : ");
scanf("%d",&size);
for(int i = 0;i<size;i++){
/*
* can't seem to figure out how to do this correctly.
*
* I know I have to use malloc(sizeof()),etc..
*
* I've only had success with creating the list backwards.
*
* In this loop there would be a scan from user input for
* the data instance
*/
}
return a;
}
所以我认为这很简单。任何帮助将不胜感激。
你可以做这样的事情。
// Get user input and store it in the list
void getValue(myStruct *ptr)
{
printf("nEnter Data:");
scanf("%d",&ptr->data);
ptr->next=NULL;
}
myStruct * create()
{
myStruct * a_head = NULL; // start of list
myStruct * a_tail = NULL; // end of list
int size,i;
printf("Enter Size of List : ");
scanf("%d",&size);
for(i=0;i<size;i++)
{
// Creating first node
if(i==0)
{
a_head=a_tail=malloc(sizeof(myStruct));
getValue(a_tail);
}
// Creating other nodes
else
{
a_tail->next=malloc(sizeof(myStruct)); // adding new node to the end of non-empty list
getValue(a_tail->next); // Insert data into the new node
a_tail=a_tail->next; // update tail pointer
}
}
return a_head;
}
在该for
循环中,您应该以某种方式创建所需的节点(可能要求用户输入并按照您所说的使用malloc()
),然后从前一个链接。在这种情况下,您可能希望保留指向列表最后一个元素的指针,因为当链接时,该元素将指向新元素。
我大学的这个项目中可以找到这方面的学术但功能实现。
#include<stdio.h>
#include<stdlib.h>
void main()
{
struct N
{
int Data;
struct N *Next;
};
typedef struct N node;
node *H, *T;
char C[100];
H=(node*)malloc(sizeof(node));
T=H;
printf("Enter numbers to create and store in Linked List, to stop storing enter 'X': ");
while(1)
{
scanf("%s", C);
if(C[0]!=' ')
{
if(C[0]!='X')
{
T->Data=atoi(C);
T->Next=(node*)malloc(sizeof(node));
T=T->Next;
T->Next=NULL;
}
else
break;
}
}
T=H;
printf("The elements in the Linked List are:");
while(T->Next!=NULL)
{
printf(" %d", T->Data);
T=T->Next;
}
printf(".n");
free(H);
free(T);
}