A chained storage structure for linear tables: In addition to storing data element information, the storage address (pointer) of its successor is the data field and the Pointer field, two parts are the storage image node (node), each node contains only one pointer field, and the single linked list
The first storage position of the node is called the head pointer, and the last node pointer is null.
The similarities and differences between the head pointer and the head node:
Empty linked list:
The data field of the head node is generally empty, but the length of the linked list can also be stored. The pointer to the head node points to the address of the first node.
In the C language, you can use a struct pointer to represent a single-linked list:
typedef struct NODE
{Elemtype data;//data field
struct *node next;//pointer field
}node;
typedef struct *NODE linklist;
P is a pointer to the AI, P->data is the data field, and P->next is the pointer field.
If p->data=ai; is p->next->data=ai+1;
C Language Write Getelem function:
Status Getelem (List l,i,*e)
{int i,j;
Linklist p;
p=l=>next;
J=1;
while (P&&j<i)
{p=p->next;
j + +;
}
if (!p| | J>i)
{return ERROR;}
*e=p->data;
return OK;
}
The time complexity of the algorithm, in the best case, I is the first element, the complexity is O (1), in the worst case, i=n needs to traverse n-1, so the complexity is O (n), and the average is O (n).
Single-linked list does not define the length of the table, do not know the number of cycles, inconvenient to use for, the use of work pointer after the idea of moving;
Single-linked list insertion problem, it is important to note that the insertion element must be assigned to the next address pointer, in order to point to their own pointer assignment, the sequence can not be reversed, otherwise it will cause a dead loop, as follows:
The node s must be inserted between the AI and the ai+1, the pointer to the AI is P,
Then,s->next=p->next;
P-next=s;
The order of the two orders cannot be reversed.
Single-linked list insert operation
Status Listinsert (linklist *l,int i, elemtype e)
{int J; Linklist s;
Linklist p=*l;
J=1;
while (P&&j<i)
{p=p->next;
j + +;}
if (!p| | J>i)
{return ERROR;}
S= (linklist) malloc (sizeof (Node));
s->data=e;
s->next=p->next;
p->next=s;
return OK;
}
Single-linked list delete operation:
Status Listdetele (linklist *l,int i,elemtype *e)
{int J; Linklist q,p;
P=*l;
J=1;
while (P->next&&j<i)
{p=p->next;
j + +;}
if (!p->next| | J>i)
{return ERROR;}
q=p->next;
p->next=q->next;
*e=q->data;
Free (q);
return OK;
}
Efficiency PK: In the algorithm of inserting and deleting frequently, the chain structure is less complex than the sequential structure. Once is the same as O (n).
For example: Insert or delete 10 elements in the element I, the sequential structure is O (n) per operation, and the chain is O (n) for the first operation, and each time it is O (1).
Data structure and algorithm learning (II.)