数据结构(08)— 线性单链表基本操作
生活随笔
收集整理的這篇文章主要介紹了
数据结构(08)— 线性单链表基本操作
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1. 線性單鏈表數(shù)據(jù)結(jié)構(gòu)
// 假定每個結(jié)點(diǎn)的類型用 SNode 表示
typedef struct SNodeTag
{int data; // 所存儲的數(shù)據(jù)元素SNodeTag *next; // 存儲后續(xù)元素的指針域
}SNode;
2. 帶頭結(jié)點(diǎn)單鏈表的基本運(yùn)算
2.1 置空表
void setnull(SNode *&h) // h 為引用型指針
{h = new SNode; // 創(chuàng)建一個頭結(jié)點(diǎn)h->next = NULL;
}
2.2 獲取長度
int lenth(SNode *h)
{int len = 0;SNode *q = h->next;while (!q) // or q != NULL{len++;q = q->next;}return len;
}
2.3 獲取單鏈表 第 i 個結(jié)點(diǎn)的地址
SNode * get(SNode *h, int i)
{if(i < 0 || i > lenth(h)-1){std::cout << "i is error" << std::endl;return NULL;}SNode *p = h->next;for(int k=0; k<i, p!= NULL; k++){p = p->next;}if(p != NULL){return p;}
}
2.4 按值查找
int locate(SNode *h, int x)
{SNode *q = h->next;for(int i=0; i<lenth(h); i++){if(q->data == x){return i;}q = q->next;}// 未找到值域等于 x 的結(jié)點(diǎn)if(q == NULL){return -1;}
}
2.5 插入結(jié)點(diǎn)
// 插入結(jié)點(diǎn),要在第 i 個位置插入 x
int insert(SNode *h, int x, int i)
{if(i < 0){std::cout << "i is error" << std::endl;return -1;}// 創(chuàng)建要插入的結(jié)點(diǎn)對象SNode *p = new SNode;p->data = x;SNode *q = h->next;// 先找到 i-1 個結(jié)點(diǎn)for(int k=0; k<i; k++){q = q->next;}p->next = q->next;q->next = p;return 0;
}
2.6 刪除結(jié)點(diǎn)
// 刪除結(jié)點(diǎn),刪除第 i 個位置的結(jié)點(diǎn)
int delnode(SNode *h, int i)
{if(i < 0 || i > lenth(h) - 1){std::cout << "i is error" << std::endl;return -1;}SNode *q = h->next;// 先找到 i-1 個結(jié)點(diǎn)for(int k=0; k<i; k++){q = q->next;}SNode *p = q->next;q->next = p->next;delete p;return 0;
}
2.7 顯示鏈表
// 顯示單鏈表
void display(SNode *h)
{SNode *p = h->next;while (p){std::cout << p->data << std::endl;p = p->next;}
}
總結(jié)
以上是生活随笔為你收集整理的数据结构(08)— 线性单链表基本操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2022-2028年中国镀金属膜行业市场
- 下一篇: 2022-2028年中国聚乳酸降解塑料行