尾插法循环链表

#include <stdio.h>
#include <stdlib.h>
#define ElemType int
struct ListNode
{
    ElemType e;
    struct ListNode *next;
};

typedef struct
{
    struct ListNode *Head;
    struct ListNode *Tail;
}List,*pList;

int insertTail(ElemType X, pList L)
{
    /*建指针,分内存,赋值*/
    struct ListNode *newP = (struct ListNode *)malloc(sizeof(struct ListNode)) ;
    if (newP == NULL )
    {
        perror("out of space!");
        return -1;
    }
    /*元素赋值*/
    newP->e = X;
    
    /*插入到链表尾部,定位新的尾指针*/
    newP->next = L->Tail->next;
    L->Tail->next = newP;

    /*鸠占鹊巢*/
    L->Tail = newP;
    return 0;
}
int main()
{
    pList L  = (pList)malloc(sizeof(List)) ;
    /*为链表分配内存*/
    if (L == NULL)
    {
        perror("out of space!");
        return -1;
    }
    /*分配尾指针*/
    L->Tail = (struct ListNode *)malloc(sizeof(struct ListNode));
    if (L->Tail == NULL)
    {
        perror("out of space!");
        return -1;
    }
     /*初始化链表*/
    L->Tail->next = L->Tail;
    L->Head = L->Tail->next;

    /*接个参*/
    int i;
    printf("来插我呀:>");
    for (; scanf("%d",&i) != EOF;)
    {
        printf("来插我呀:>");
        insertTail(i,L);
    }        
    /*遍历节点*/
    while (L->Head->next != L->Tail->next)
    {
        printf("%d ", L->Head->next->e);
        L->Head = L->Head->next;
    }
    printf("\n%d ",L->Tail->e);
    puts("\nojbk!");
    return 0;
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值