链表
1. 定义一个链表
- 数据项
- 下一个节点的地址
struct node
{
int data ;
struct node* next ;
}
2. 插入数据
头添加
void add_to_head(struct node** , struct node** end , int idata)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
if(temp != null)
{
temp->data = idata;
ptemp->next = null;
if()
{
*end = temp;
}
else
{
temp->next = *head;
}
*head = temp ;
}
}
尾添加
void add_to_end(struct node** , struct node** end , int data)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
if(temp != null)
{
temp->data = idata;
ptemp->next = null;
if(*head == null)
{
*head = temp;
}
else
{
(*end)->next = temp;
}
*end = temp;
}
中间插入
void add_to_middle(struct node** head, struct node** end, int index , int idata)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
if(temp != null)
{
temp->data = idata;
ptemp->next = null;
if(index == 0)
{
add_to_head(head,end,idata);
}
else
{
struct node* temp = findbyindex(*head,index);
if(temp != null)
{
struct node* pt =(struct node*)malloc(sizeof(struct node));
if(pt != null)
{
pt->data = idata;
pt->next = null;
pt->next = temp->next;
temp->next = pt;
}
}
}
}
3. 查找节点
根据下标查找节点
int find_by_index(struct node* head , int index)
{
int num = 1;
while(head!=null)
{
if(index == num)
{
return head;
}
num++;
head=head->next;
}
return null;
}
根据数据查找节点
int find_by_index(struct node* head , int index)
{
while(head!=null)
{
if(head->data == idata)
{
return head;
}
head=head->next;
}
return null;
}
4. 删除节点
头删除
void delete_head(struct node** head , struct node** end)
{
if(*head == null)
{
return ;
}
if((*head)->next == null)
{
free(*head);
}
else
{
struct node* pt = *head;
head = (*head)->next;
free(pt);
}
}
尾删除
void delete_end(struct Node** Head, struct Node** End)
{
if (*Head == NULL)
{
return;
}
if ((*pHead)->pNext == NULL)
{
free(*pHead);
*pHead = NULL;
*pEnd = NULL;
}
else
{
struct Node* pt = *pHead;
while (pt->next != *end)
{
pt = pt->next;
}
free(*end);
*end = pt;
(*end)->next = NULL;
}
}
中间删除
void delete_middle(struct node** head, struct node** end,int idata)
{
struct node* temp = *head;
while(temp->next != null)
{
if(temp->next->data == idata)
{
break;
}
temp=temp->next;
}
if(temp->next != null)
{
struct node* pt = temp->next;
temp->next = pt->next;
free(pt);
}
else
{
printf("查无此节点");
}
}
5. 修改元素
修改制定数据
void change_by_daya(struct node* head , int data1 , int data2 )
{
struct node* temp = find_by_data(head,data1)
{
if(temp. != null)
{
temp->data = data2 ;
}
}
}
修改指定下标的数据
void change_by_index(struct node* head , int index , int data)
{
struct node* temp = find_by_index(phead,data)
if(temp != null)
{
temp->data = data;
}
}
双向链表
双向链表的定义
struct Node
{
int Data;
struct Node* PNext;
struct Node* Pre;
};