顺序链表 : 在任意位置添加节点

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

typedef struct node{

        char value;
        struct node *next;

}node, *Linklist;


void printLinklist(Linklist l)
/* print the linklist to screen  : Rong Tao */
{

        Linklist tmp = l;

        printf("\n-----------print---------\n");

        do{
                printf("%c",tmp->value);

                tmp = tmp->next;

        }while(tmp->next != NULL);

        printf("\n");
}

int getLength(Linklist L)
/* get the Linklist length  : Rong Tao */
{
        struct node *n = L;

        int length = 0;

        do{

                length++;
        
                n = n->next;                

        }while(n->next != NULL);

        return length - 1;
}

void initLinklist(Linklist l)
/* initial linklist with scanf  : Rong Tao */
{
        struct node *tail = malloc(sizeof(struct node));

        scanf("%c",&l->value);

        l->next = tail;

        
        struct node *tmp;
        do{
                tmp = malloc(sizeof(struct node));

                scanf("%c",&tmp->value);

                tail->next = tmp;

                tail = tmp;

                tmp = NULL;

        }while(tail->value != 'q');

}

void addNode(Linklist head)
/* add node to linklist  : Rong Tao */
{

        int dim;
        char ch;
        int len = getLength(head);

        printf("(dim,char): ");
        scanf("%d%c",&dim,&ch);

        if(dim<0||dim>len){

                printf("Out of array boundary!\n");
                exit(0);
        }

        struct node *tmp = malloc(sizeof(struct node));

        tmp->value = ch;

        int i = 0;
        Linklist L = head;

        if(dim == 0){

                tmp->next = L;
                head = tmp;

        }else {

                do{
                        i ++;

                        L = L->next;

                }while(i < dim);

                tmp->next = L->next;
                L->next = tmp;
        }


}


void main(){

        Linklist head = malloc(sizeof(struct node));


        initLinklist(head);

        printLinklist(head);

        addNode(head);

        printLinklist(head);


}












已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页