单链表 插入,删除 C/C++
作者:互联网
#include<iostream>
using namespace std;
typedef struct Link_Node{
int data;
Link_Node* next;
} ;
// 单链表的插i入操作,插入到第K个元素后面,link_list 是单链表的首指针
// 有可能List,
int insert_data(Link_Node *link_list,int k,int data)
{
Link_Node *p_node = link_list;
int i = 0;
while(p_node&&i<k){
i++;
p_node = p_node->next;
}
if(!p_node) return 0; // 没有第K个元素,插入位置无效
// 已经到了第k个元素,把新值放在第K 个值 后面。
//p_node 是第K个节点,将data放在 p_node 之后。
Link_Node *next_k_node = (Link_Node*)malloc(sizeof(Link_Node));
next_k_node->next = p_node->next;
next_k_node->data = data;
p_node->next = next_k_node;
return 1;
}
int delete_data(Link_Node *link_list,int k)
{
int i = 0;
Link_Node *p_node = link_list;
while(p_node&&i<k-1){
i++;
p_node = p_node->next;
}
if(!p_node&&!p_node->next) return 0; //没有第K个元素,插入位置无效
Link_Node *del_node = p_node->next;
p_node->next = del_node->next;
free(del_node);
return 1;
}
int main()
{
Link_Node *p = (Link_Node*)malloc(sizeof(Link_Node)); // 头结点
Link_Node *current = p;
for(int i = 0 ; i <10 ;i++){
Link_Node *p_node = (Link_Node*)malloc(sizeof(Link_Node));
p_node->data = i;
p_node->next = NULL;
current->next = p_node;
current = current->next;
}
insert_data(p,10,10);
current = p;
while(current=current->next){
cout<< current->data<<endl;
}
delete_data(p,9);
current = p;
while(current=current->next){
cout<<current->data<<endl;
}
insert_data(p,8,8);
current = p;
while(current=current->next){
cout<<current->data<<endl;
}
return 0;
}
标签:node,Node,单链,C++,next,current,插入,Link,data 来源: https://www.cnblogs.com/daniel123/p/16279161.html