linux C学习笔记03--单链表

单链表一直是程序员的基础,我也来复习下,下面是link.c中的代码,供main.c 调用,代码很简单,单链表的插入,删除,查找和遍历输出,

#include <stdio.h>
#include <stdlib.h>


typedef struct link{
    int data;
    struct link* next;
}*LINK;

int insert_link(LINK* head,int data);
int print(LINK head);
int delete_node(LINK *head,int n);
int find_node(LINK head,int n);


int insert_link(LINK* head,int data)
{
    LINK node = (LINK)malloc(sizeof(struct link));
    LINK tmp = NULL;

    if(node != NULL)
    {
        node->data = data;
        node->next = NULL;
    }
    else
    {
        printf("malloc new node error!\n");
        return -1;
    }

    if(*head == NULL)
    {
        *head = node;
        return 0;
    }

    tmp = *head;
    while(tmp->next != NULL)    //find ending node
    {
        tmp = tmp->next;
    }
    tmp->next = node;

    return 0;
}

int print(LINK head)
{
    LINK tmp = head;
    while(tmp != NULL)
    {
        printf("%d \n",tmp->data);
        tmp = tmp->next;
    }

    return 0;
}

int    delete_node(LINK *head,int n)    //delete the node of index is n
{
    LINK tmp = *head;
    LINK save = tmp;
    int i = 0;

    if(n == 1)
    {
        tmp = tmp->next;
        free(save);
        *head = tmp;
        return 0;
    }

    while(tmp != NULL)
    {        
        if(i == n-1)    
{ save->next = tmp->next; free(tmp); break; } save = tmp; tmp = tmp->next; i++; } if(n-1 > i) { printf("error: delete %d is out of length\n",n); return -1; } return 0; } int find_node(LINK head,int n) { LINK tmp = head; int data = 0; int i = 0; while(tmp != NULL) { if(i == n-1) { data = tmp->data; break; } tmp = tmp->next; i++; } if(n-1 > i) { printf("find_node error: out of link length\n"); return -1; } return data; }

接着是main.c:

#include <stdio.h>
#include <stdlib.h>

typedef struct link{
    int data;
    struct link* next;
}*LINK;

extern int insert_link(LINK* head,int data);
extern int print(LINK head);
extern int delete_node(LINK *head,int n);
extern int find_node(LINK head,int n);

int main(int argc,char* argv[])
{
    LINK phead = NULL;
    
    insert_link(&phead,1);
    insert_link(&phead,2);
    insert_link(&phead,3);
    insert_link(&phead,4);
    insert_link(&phead,5);
    insert_link(&phead,6);

    print(phead);
    delete_node(&phead,1);                //delete the node by index
    print(phead);
    delete_node(&phead,2);                //delete the node by index
    print(phead);
    delete_node(&phead,1);                //delete the node by index
    print(phead);

    printf("find node 6 is %d\n",find_node(phead,6));        //finding the node by index

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值