連結串列插入的三種方式
連結串列的插入:
一、頭插
1、判斷空鏈 :
a:新節點指向NULL
b: 頭指向新節點
2、非空鏈
a: 新節點指向頭(第一個節點)
b: 頭指向new
綜上: 不需判斷直接在頭操作
程式碼:
void insert_head(Node * head , Node new)
{
new = * head;
* head = new;
}
二、中間插
1、判斷空連結串列
2、非空
遍歷找位置
找到 未找到
是頭 不是頭
是頭:
new -> next = * head;
* head = new;
不是頭:
new -> next = pre -> next;
pre -> next = new;
未找到:(補在鏈尾,此時cur為鏈尾指向的NULL)
pre -> next = new
new -> next = NULL
程式碼:
void insert_mid(Node * head , Node new)
{
Node * cur = NULL;
Node * pre = NULL;
if(* head == NULL)
{
printf(“it is empty\n”);
return;
}
else
{
cur = * head;
放前面
while(cur != NULL && cur -> data != new -> data)
{
pre = cur;
cur = cur -> next;
}
if(cur == NULL)
{
pre -> next = new;
new -> next = NULL;
}
else
{
if(* head == cur)
{
new -> next = * head;
* head = new;
}
else
{
new -> next = pre -> next;
pre -> next = new;
}
}
}
三、尾插
1、判斷空鏈
a、插入第一個節點
2、非空鏈
a、找到鏈尾
b、將新節點插入鏈尾
程式碼:
void insert_tail(Node * head , Node new)
{
Node * cur = NULL;
if(* head == NULL)
{
printf(“it is empty\n”);
return;
}
else
{
cur = * head;
while(cur != NULL )
{
cur = cur -> next;
}
cur -> next = new;
new -> next = NULL;
}
}