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