*/ /*尾插法建立单链表*/ LinkList CreateList(int n) { LinkList head, s, p; head = (LinkList)malloc(sizeof(LNode)); head->next = NULL; p = head; return head; }
时间: 2023-05-26 17:02:12 浏览: 55
To implement the tail insertion method for creating a singly linked list in C, you can use the following code:
typedef struct LNode{
int data;
struct LNode *next;
}LNode, *LinkList;
LinkList CreateList(int n) {
LinkList head, s, p; // declare three pointers: head, s, and p
head = (LinkList)malloc(sizeof(LNode)); // allocate memory for head
head->next = NULL; // set the next pointer of head to NULL
p = head; // let p point to head initially
int i;
for(i=1; i<=n; i++) {
s = (LinkList)malloc(sizeof(LNode)); // allocate memory for the new node
printf("Please enter the data of node %d: ", i);
scanf("%d", &(s->data)); // read the data for the new node
s->next = NULL; // set the next pointer to NULL
p->next = s; // insert the new node after the last node
p = s; // let p point to the last node now
}
return head; // return the head pointer of the new linked list
}
In the above code, you first define the structure of a singly linked list and two pointers: head and p. Then, you allocate memory for the head node and set its next pointer to NULL. After that, you loop through n times to create n new nodes. For each new node, you allocate memory for it, read its data from user input, set its next pointer to NULL, and insert it after the last node of the current list. Finally, you return the head pointer of the new linked list.