單鏈表的基本操作
包括:初始化,插入,刪除,逆置,求表長
- 定義鏈表的數據結構
struct node {
int data;
node *next;
};
- 初始化鏈表
node* create(node* head) {
head = new node;
head->next = NULL;
return head;
}
- 鏈表的插入(頭插法)
node* insert(node *head, int value) {
//new node
node *new_node = new node;
new_node->data = value;
//record head->next
node *temp;
temp->next = head->next;
head->next = new_node;
new_node->next = temp->next;
return head;
}
- 鏈表的刪除,刪除第i個節點,(有一個空的頭結點作爲第0個)
//測試集,空指針,空鏈表,刪除的位置是負數,刪除的位置在鏈表中,刪除的位置超過鏈表的長度
node* delete_by_position(node *head, int n) {
//空指針
if(!head) {
cout<<"NULL point!"<<endl;
return head;
}
//指針應該定位到第n-1個元素
node *p = head;
//已經數了多少個了,因爲要刪除第n個元素 ,所以應該數了n-1次,然後p指針指向第n-1個元素
int count = 0;
//move to position of n-1
while(p->next && n-1>count) {
p = p->next;
count++;
}
if(n-1 != count || !p->next) {
cout<<"node not found!"<<endl;
return head;
}
//if found, delete that node
node* temp = p->next;
p->next = temp->next;
delete temp;
return head;
}
- 鏈表的刪除,刪除節點值爲value的第一個元素
//測試集,空指針,空鏈表,刪除的元素在鏈表中,刪除的元素不在鏈表中
node* delete_by_value(node* head, int value) {
if (!head) {
cout<<"node not found!"<<endl;
return head;
}
bool flag =false;
node *p = head;
while (p->next) {
if (p->next->data == value) {
flag = true;
break;
}
p = p->next;
}
if(flag) {
node* temp = p->next;
p->next = temp->next;
free temp;
} else {
cout<<"node not found!"<<endl;
}
return head;
}
- 遍歷鏈表
void display (node *head) {
if(!head) {
return ;
}
node* p = head;
while(p->next) {
cout<<p->next->data<<endl;
p = p->next;
}
}
- 求鏈表的長度
int getLength(node *head) {
if (!head) {
return -1;
}
int count = 0;
node *p = head;
while(p->next) {
count++;
p = p->next;
}
return count;
}
- 鏈表逆置 這裏採用原地逆置,通過頭指針和額外定義的兩個指針不斷移動更改鏈接來實現逆置
node* reverse(node *head) {
//NULL point
if(!head) {
cout<<"it is NULL point!"<<endl;
return head;
}
node *a,*p;
//initialize
a = head->next;
while(a->next) {
p = a->next;
a->next = p->next;
p->next = head->next;
head->next = p;
}
return head;
}
主函數
int main () {
//new head
node* head;
//創建頭結點
head = create(head);
//輸入n個元素,並以頭插的形式插入到鏈表
int n;
cin>>n;
while(n-->0) {
int value;
cin>>value;
head = insert(head,value);
}
//遍歷
display(head);
//刪除第n個元素 注意n取值
cin>>n;
head = delete_by_position(head,n);
//刪除元素值爲value的第一個節點
int value;
cin>>value;
head = delete_by_value(head,value);
//鏈表逆置
head = reverse(head);
display(head);
//求表長
cout<<getLength(head)<<endl;
display(head);
return 0;
}