单链表逆置

 

link reverse

 

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

#define NAME_MAX_LEN (100)

typedef struct student{
    char name[NAME_MAX_LEN];
    int numb;
    struct student *pNext;
}Node;

/* 需要3个临时指针变量,从link头开始反转,直到最后一个元素返回 */
Node* transpose(Node* pListHeadHead){
    if((pListHeadHead==NULL) || (pListHeadHead->pNext==NULL))
    {
        puts("node less than two, return NULL");
        return NULL;
    }

    Node *pFirst, *pMid, *pLast;
    pFirst=pListHeadHead;
    pMid=pFirst->pNext;
    pLast=pMid->pNext;

    pFirst->pNext=NULL;
    pMid->pNext=pFirst;
    //前两个元素反转完成。
    while(pLast){
        pFirst=pMid;
        pMid=pLast;
        pLast=pMid->pNext;
        pMid->pNext=pFirst;
    }
    return(pMid);
}

Node* crateList();
void printList(Node* pListHead);

int main()
{
    Node* pListHead;
    pListHead=crateList();
    printList(pListHead);
    puts("----------transpose---------");
    pListHead=transpose(pListHead);
    printList(pListHead);
    return 0;
}
Node* crateList(){
    Node *pHead=NULL, *pCurrent, *pPre;
    char input[NAME_MAX_LEN];
    puts("enter node.name");
    //while(gets(input)!=NULL && input[0]!='\0')
    //空输入,gets返回'\0', fgets 返回 '\n', 两条语句等价,空输入都能退出
    while(fgets(input, NAME_MAX_LEN, stdin) != NULL && input[0]!='\n')
    {
        pCurrent=(Node*)malloc(sizeof(Node));
        if(pCurrent==NULL)
            return(0);
        if(pHead==NULL)
            pHead=pCurrent;
        else
            pPre->pNext=pCurrent;
        pCurrent->pNext=NULL;
        strcpy(pCurrent->name,input);
        puts("enter node.number:");
        scanf("%d",&pCurrent->numb);
        pPre=pCurrent;
        puts("enter the next one or enter to leave");
        while(getchar()!='\n')
        {
            puts("get char");
            continue;
        }
    }
    return(pHead);
}
void printList(Node* pListHead){
    Node* pCurrent;
    pCurrent=pListHead;
    if(pCurrent==NULL)
        puts("no data enter!");
    else
        while(pCurrent!=NULL){
            printf("the name is %s,and number is %d\n",pCurrent->name,pCurrent->numb);
            pCurrent=pCurrent->pNext;
        }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值