虎贲小队程序猿

get along

导航

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;
}

 

posted on 2015-05-29 11:02  jjssl  阅读(234)  评论(0编辑  收藏  举报