#include <stdio.h> #include <malloc.h> #include <stdbool.h>/** * * Definition of linked list node * * typedef struct node{int dat
a;//data domain struct node * pnext;//pointer field, storing the address of the next node} node, * PNODE;
/** * * Create a linked list */Pnode create_list () {int len,i;
printf ("Please enter the length of the list: len=\n");
scanf ("%d", &len);
Pnode phead=malloc (sizeof (Node));
phead->pnext=null;
Pnode Ptail=phead;//ptail is a pointer to the tail node for (i=0;i<len;i++) {int val;
printf ("Please enter the value of the%d element:", i+1);
scanf ("%d", &val);
Pnode pnew=malloc (sizeof (Node));
pnew->data=val;
pnew->pnext=null;
ptail->pnext=pnew;
Ptail=pnew;
return phead;
/** * * Traversal of linked lists/void traverse (Pnode phead) {Pnode p=phead->pnext;
while (P!=null) {printf ("%d", p->data);
p=p->pnext;
printf ("\ n");
/** * Determine if the list is empty/bool IsEmpty (Pnode phead) {if (Null==phead->pnext) {return true; }else{return FALse
/** * * Get the length of the list */int list_num (Pnode phead) {int num=0;
Pnode p=phead->pnext;
while (p!=null) {num++;
p=p->pnext;
return num; /** * Insert elements into the list/bool Insert_list (Pnode phead,int val, int pos) {//need to find the POS position and need to determine if POS is legitimate//i is the position of the node P refers to, so from the beginning, for
What to Pos-1, because the use is while when i=pos-1 out of the loop int i=0;
Pnode P=phead;
while (null!=p&&i<pos-1) {i++;
p=p->pnext; //If the insertion position is too large, then p=null,//If the insertion position is 0 or negative, then i>pos-1 if (i>pos-1| |
null==p) {printf ("invalid insert location \ \ \ n");
return false;
} pnode Pnew=malloc (sizeof (Pnode));
pnew->data=val;
Pnode temp=p->pnext;
p->pnext=pnew;
pnew->pnext=temp;
return true;
/** * * Delete node in the list/delete (Pnode phead,int pos, int * pval) {int i=0;
Pnode P=phead;
We want to delete the node behind P, so p cannot point to the last node P->next!=null while (p->pnext!=null&&i<pos-1) {p=p->pnext;
i++; } if (i>pos-1| |
P->pnext==null) {printf ("delete location is illegal \ n");return false;
} Pnode temp=p->pnext;
p->pnext=temp->pnext;
Free (temp); int main () {Pnode phead= create_list (); if (IsEmpty (phead)) printf ("list is empty \ n"); printf ("The length of the linked list is:%d\n", List_num (Phead)); t
Raverse (Phead);
Insert_list (phead,55,1);
int Val;
Delete (phead,6,&val);
Traverse (Phead);
return 0;
}