Definition and representation of singly linked list

  • Singly linked list storage structure
typedef struct Lnode{
ElemType    data;
struct    Lnode   *next;
}Lnode,*LinkList

insert image description here

  • Initialization of the singly linked list
    (1) Generate a new node as the head node, use the head pointer L to point to the head node
    (2) empty the pointer field of the head node.

Algorithm Description

Status InitList_L(LinkList &L){
  	L=new LNode;
  	L->next=NULL;
  	return OK;
}
  • Determine whether the linked list is empty:
    an empty list means that there is no element in the linked list, but the head pointer and head node still exist.
    Idea: determine whether the head node pointer field is empty
int ListEmpty(LinkList L){
	if(L->next)
		return 0;
	else
		return 1;
}

Returns 1 if L is an empty list, otherwise returns 0.

  • Singly linked list destruction
    idea: starting from the head pointer, release all nodes in turn
Status DestroyList_L(LinkList &L){
	Lnode *p;
	while(L){
		p=L;
		L=L->next;
		delete p;
	}
}
  • Clear the linked list
    The linked list still exists, but there are no elements in the linked list Idea
    : release all nodes in turn, and set the head node pointer field to empty
Status ClearList(LinkList &L){
	Lnode *p,*q;
	p=L->next;
	while(p){
		q=p->next;
		delete p;
		p=q;
	}
	L->next=NULL;
	return OK;
}
  • Find the length of the singly linked list L
int ListLength_L(LinkList L){
	LinkList p;
	p=L-next;
	i=0;
	while(p){
		i++;
		p=p->next;
	}
}
  • Value-take the content of the i-th element in the singly linked list
    Linked list is not a random access structure, so it needs to search down one by one node.
    Algorithm steps:
  1. Scan along the chain from the first node (L->next), use the pointer p to point to the currently scanned node, and the initial value of p=L->next.
  2. j is used as a counter to accumulate the number of nodes currently scanned, and the initial value of j is 1
  3. When p points to the next node scanned, the counter j is incremented by 1.
Status GetElem_L(LinkList L, int i, ElemType &e){
	p=L->next;   j=1;
	while(p&&j<i){
		p=o->next;++j;
	}
	if(!p||j>i)
		return ERROR;
	e=p->data;
	return OK;
}
  • Insert node
    Insert a new node with value e before the i-th node
    Algorithm diagram:
    insert image description here
    code:
Status ListInsert_L(LinkList &L,int i, ElemType e){
	p=L;j=0;
	while(p&&j<i-1){
		p=p->next;++j;
	}
	if(!p||j>i-1)
		return ERROR;
	s=new LNode;
	s->data=e;
	s->next=p->next;
	p->next=s;
	return OK;
}
  • delete node

insert image description here

Guess you like

Origin blog.csdn.net/qq_45257495/article/details/131631336