C語言(5) 鍊錶操作

2021-07-04 02:51:35 字數 1687 閱讀 3125

1.顯示鍊錶元素

(1)把鍊錶首結點作為當前結點;

(2)判斷當前結點是否為null,為null則輸出結果;

(3)輸出當前結點的值;

(4)把鍊錶的下一結點作為當前結點;

(5)重複執行步驟(1)~(3)。

例.編寫乙個函式,顯示head指向開始結點的鍊錶所有元素。

struct snode

; void write(struct snode *p)

}

2.刪除鍊錶中指定值的結點

(1)如果首結點是要刪除的結點,則刪除首結點,返回新的首結點位址

(2)找到要刪除的結點

(4)返回原首結點位址

例.編寫乙個函式,刪除head指向開始結點的鍊錶中值為num的下乙個結點。

struct snode

; struct snode *delete_node(struct snode *head,int num)

else

if(p2->num==num)

} return head;

}

3.建立有序列表

把乙個結點插入到公升序的鍊錶,仍保持原來的鍊錶的公升序不變。

(1)建立乙個新結點

(2)如果鍊錶為空或者首結點值小於插入的結點

①新結點插入到首結點之前

②返回新的首結點位址

(3)查詢鍊錶,找到比插入點大的結點或鍊錶尾

(4)如果到了鍊錶尾,則新結點插入到鍊錶尾

(5)如果不是鍊錶尾,插入到找到的比較大的結點的前面

(6)返回頭結點的位址

例.編寫乙個函式,在head指向開始的結點的公升序鍊錶中,插入值為num的乙個結點,儲存鍊錶的公升序不變

struct snode

; struct snode *insert_node(struct snode *head,int num)

p2=p1=head;

while(p->num>p2->num&&p2->next)//查詢大於等於插入元素的結點

if(p2->next==null)

else

return head;

}

//將單鏈表中前m個結點和後n個結點互換,m+n=10

m=4;

n=6;

k=0;

p=head;//head為頭結點

while (1)

k++;

if (m+1==k)

s=p;//s為原煉表尾結點

p=p->next;

}s1=head->next;

head->next=q->next;

s->next=s1;

q->next=null;

//釋放所有結點

p=head->next;//head為頭結點

while(1)

else

} //從小到大排序

for (p=head;p!=null && p->next!=null;p=p->next) else

C語言鍊錶綜合操作

預處理命令 include include define len sizeof struct student define format ld,f define p format ld 5.1f n define null 0 構造結構體 struct student 構造乙個結構體型別 int n...

鍊錶操作集合 C語言

主要是給自己以後複習知識,還有進行修改優化用的 歡迎批評,其中鍊錶合併的就地合併我並未掌握,我用了新的頭結點以後要補上 首先是標頭檔案定義 ifndef andrew define andrew include include include include include define size ...

C語言 之鍊錶操作

常見資料結構有 表棧 佇列樹鍊錶相對於陣列有很多優點,現在總結一下鍊錶的常用操作。1.單鏈表新增節點 include include includestruct list node typedef struct list node list one list one head null 定義乙個全域...