链表的基本操作。。。

来源:互联网 发布:陌陌切图软件 编辑:程序博客网 时间:2024/06/01 11:19
#include "node.h"

/*打印链表*/
void print(node* head)
{
    if(head == NULL)
        printf("链表为空\n");
    printf("链表数据依次为:");
    while(head != NULL)
    {
        printf("%d ",head->data);
        head = head->next;
    }
    printf("\n");
}

/*从尾部插入*/
void insert_tail(node** head,const int d)
{
    node* t = *head;
    node* p = (node*)malloc(sizeof(node*));
    p->data = d;
    if(*head == NULL)
    {
        *head = p;
        p->next = NULL;
        return;
    }
    while(t->next != NULL)
    {
        t = t->next;
    }
    t ->next = p;
    p ->next = NULL;
}
/*从头部插入*/
void insert_head(node** head,const int d)
{
    node* p = (node*)malloc(sizeof(node*));
    p -> data = d;

    if((*head) == NULL)
    {
        (*head) = p;
        p ->next = NULL;
        return;
    }
    p->next = *head;

    *head = p;
}
/*指定位置插入*/
void insert_pos(node** head, int pos,const int d)
{
    node* t = *head;

    node* p =(node*)malloc(sizeof(node*));
    p -> data = d;
    if(pos > (size(*head)+1))    
    {
        printf("位置输入有误,请重新输入\n");
        return ;
    }
    if(*head == NULL)
    {
        (*head) = p;
        p->next = NULL;
        return ;
    }
    while(pos-1)  /*找到pos位置*/
    {
        t = t->next;
        pos--;
    }
    p->next = t->next;
    t->next = p;
}
/*指定位置删除*/
void del_pos(node** head,int pos)
{
    node* t = *head;
    if(pos > size(*head) || pos == 0)    
    {
        printf("位置输入有误,请重新输入\n");
        return ;
    }
    if(pos == 1)
    {
        node* fre = *head;
        (*head) = t->next;
        free(fre);
        return ;
    }
    while(pos - 2)  /*找到要删除节点的前一个节点*/
    {
        t = t->next;
        pos--;
    }
    node* fre = t->next;
    t->next = fre->next;
    free(fre);
}
/*链表长度*/
int size(node* head)
{
    int n = 0;
    while(head != NULL)
    {
        head = head ->next;
        n++;
    }
    return n;
}

/*反转链表*/
void rev(node** head)
{
    node* p1 = *head;
    node* p2 = p1->next;
    node* tmp = NULL;  
    
    while(p2 != NULL)
    {
        tmp = p2->next;
        p2->next = p1;

        p1 = p2;
        p2 = tmp;
    }
    (*head)->next = NULL;
    *head = p1;
}
0 0
原创粉丝点击