鍊錶的基本操作(插入,刪除,排序 逆置等)

2021-07-28 01:30:44 字數 1481 閱讀 9002

鍊錶是資料結構中最基本的,也是非常經典的,在面試筆試中也是經常出現的題,但是萬變不離其宗,只要掌握了基本的操作,一起盡在掌控。

特別要注意的一點是處理時千萬要把是否為頭進行判斷,做為乙個特例,或者建立鍊錶就先固定建立乙個表頭,這樣**就沒這麼多判斷了。

#includeusing namespace std;

struct node

};class list

; //析構函式

~list()

} //新建鍊錶

void createlist()

n1 = new node(v);

current->next = n1;

current = current->next;

++size;

} }//判斷是否為空鍊錶

bool isempty()

//插入乙個節點,遇到的第乙個大於節點值之前

void insertnode(int val)

if (head->val > val)

node *current = head->next;

node *previous = head;

while (current && (current->val < val))

node *temp = new node(val);

previous->next = temp;

temp->next = current;

++size;

} //列印鍊錶

void printlist()

cout << endl;

} //刪除乙個節點

void deletenode(int val)

previous = current;

current = current->next;

} if (!current)

if (current == head)

else

delete current;

--size;

cout << "node deletes successfully!" << endl;

} //列表增序排序,插入排序

void sortlist()

if (ln != current)

else

}previous = current;

current = current->next;

} }};int main()

//鍊錶逆置

void reverse()

node *next = current->next;

head->next = null;

while (next)

head = current;

head->next = previous;

printlist();

}

鍊錶基本排序 逆置 冒泡 選擇 插入

單向鍊錶的反序圖示 1 2 3 n null 原鍊錶 1 next 2 next 3 next n next head head 1 next 2 next 3 next n next null 1 2 3 n 反序後的鍊錶 反序也就是頭指標指向最後乙個結點,然後最後乙個結點指向倒數第二個結點,以此...

鍊錶的建立 插入 刪除 排序和逆置

鍊錶的結構定義 typedef struct linkedlist node 鍊錶的建立 node create const char ch phead next null return head node create int len else phead next null return hea...

鍊錶的建立,插入,刪除,逆置運算

include typedef struct numlist,link link create 鍊錶的建立 return head 返回頭結點 link delete link head 鍊錶的刪除 q next p next 要刪除結點的前乙個結點指向要刪除結點的後乙個結點 p next retu...