C语言 链表基本函数
#include <stdio.h>
#include <malloc.h>
typedef struct my_node mynode;
struct my_node{
struct my_node *next;
int data;
};
void push_node(mynode **head,int data)
{
mynode *temp = *head;
if(*head == NULL)
{
*head = (mynode *)malloc(sizeof(mynode));
(*head) ->data = data;
(*head) ->next = NULL;
}
else
{
while(temp ->next != NULL)
temp = temp ->next;
temp ->next = (mynode *)malloc(sizeof(mynode));
temp ->next ->data = data;
temp ->next ->next = NULL;
}
}
void pop_node(mynode **head)
{
mynode *temp = *head, *prev;
while(temp ->next != NULL)
{
prev = temp;
temp = temp ->next;
}
free(prev ->next);
prev ->next = NULL;
}
void del_node(mynode **head,int index)
{
mynode *temp = *head, *tmp;
while(index -- != 1)
temp = temp ->next;
tmp = temp ->next;
temp ->next = temp ->next->next;
free(tmp);
}
void ins_node(mynode **head,int index,int data)
{
mynode *temp = *head, *tmp;
while(index -- != 1)
temp = temp ->next;
tmp = temp ->next;
temp ->next = NULL;
temp ->next = (mynode *)malloc(sizeof(mynode));
temp ->next ->next = tmp;
temp ->next ->data = data;
}
int find_data(mynode *head,int data)
{
mynode *temp = head;
int i =0;
while(temp ->next != NULL)
{
if(data == temp ->data)
return i;
temp = temp ->next;
i++;
}
return 0;
}
void back_ward(mynode **head)
{
mynode *now = *head, *temp, *prev;
while(now ->next != NULL)
{
temp = now->next;
if(now == *head)
now->next = NULL;
else
now ->next = prev;
prev = now;
now = temp;
}
now ->next = prev;
*head = now;
}
void sort_node(mynode **head)
{
mynode *curNode = (*head) ->next,*prevNode,*nextNode,*tempNode;
(*head) ->next =NULL;//有序节点尾为null
while(curNode != NULL)
{
tempNode = curNode->next;
if(curNode ->data > (*head) ->data)//大于头结点,新头结点
{
curNode->next = *head;
(*head) = curNode;
}
else
{
prevNode = *head;
nextNode = (*head) ->next;
while(nextNode != NULL && curNode ->data < nextNode->data) //定位需要插入的位置
{
prevNode = nextNode;
nextNode = nextNode ->next;
}
curNode ->next = prevNode ->next;
prevNode ->next =curNode;
}
curNode = tempNode;
}
}
int main()
{
mynode *head = NULL;
// head = (mynode *)malloc(sizeof(mynode));
// head ->data =10;
// head ->next = NULL;
push_node(&head,10);
push_node(&head,100);
push_node(&head,101);
push_node(&head,102);
push_node(&head,103);
pop_node(&head);
push_node(&head,103);
del_node(&head,2);
ins_node(&head,2,101);
find_data(head,102);
back_ward(&head);
back_ward(&head);
sort_node(&head);
return 0;
}