Data structure notes-initialization and value of singly linked list

Send a complaint, I really didn't think that I would be thrown up in online classes.

I really realized it. After a month of decadence, I finally found that reading is more effective than video

What is a singly linked list

A singly linked list is a chained access data structure that uses a set of storage units with arbitrary addresses to store the data elements in the linear list. The data in the linked list is represented by nodes. The composition of each node: element (the image of the data element) + pointer (indicating the storage location of the subsequent element), the element is the storage unit for storing data, and the pointer is connected to each The address data of the node.
- Baidu Encyclopedia

The structure of a singly linked list

  1. Data (ElementType)

  2. Node

    1. Data field
    2. Pointer field

In general, in order to facilitate processing, a node is attached before the first node of the singly linked list, which is called the head node .

The head node is a node attached before the head node, and its pointer field points to the head node. When the data element of the head node is an integer, the length of the linear table can be stored in the data field of the head node

The head pointer is a pointer to the first node in the linked list. If the linked list has a head node, the node pointed by the head pointer is the head node of the linear table; if the linked list does not have a head node, the node pointed by the head pointer is the head node of the linear table

Related code notes

#include <stdio.h>
typedef struct {
    
    
	int id;
	char* name;
}ElementType;//元素
typedef struct LNode {
    
    
	ElementType data;//结点的数据域
	struct LNode* next;//结点的指针域
}LNode, * LinkList;//*LinkList等价于struct LNode *
/*链表的初始化*/
bool InitList(LinkList& L)
{
    
    
	L = new LNode;//生成新结点作为头结点,用头指针L指向头结点
	L->next = NULL;//头结点的指针域置空
	return true;
}
/*链表的取值*/
/*
*LinkLisk L 头指针
*int i 查找第几个元素 从1开始(不包括头指针)
*ElementType& e 将找到的元素赋给e
*/
int GetElem(LinkList L, int i, ElementType& e)
{
    
    	/*
	在带头结点的单链表L中根据序号i获取元素的值,用e返回L中第i个数据元素的值
	1.用指针p指向首元结点,用j做计数器初值赋为1
	2.从首元结点开始依次顺着链域next向下访问,只要指向当前结点的指针p不为空(NULL),并且没有
	到达序号为i的结点,则循环执行以下操作
		p指向下一个结点
		计数器j相应加1
		退出循环时,如果指针p为空,或者计数器j大于i,说明指定的序号i值不合法
		(i大于表长n或i小于等于0),取值失败返回-1;否则取值成功,此时j=i时,p
		所指的结点就是要找的第i个结点,用参数e保持当前结点的数据域,返回1。
	
	*/
	LNode* p =L->next;				//初始化,p指向首元结点,计数器j初值赋为1
	int j = 1;									//计数器j相应加1
	while (p != nullptr && j < i) {
    
    
		p = p->next;
		++j;
	}
	if (p == nullptr || j > i) {
    
    //判断p是否为空指针即判断了i是否大于n了, 判断j>i是判断i是否合法
		return -1;//i值不合法 i>n或i<=0
	}
	e = p->data;
	return 1;
}

Guess you like

Origin blog.csdn.net/WildSky_/article/details/105245211