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