学习笔记:三指针实现单链表逆置
在不能使用双向链表的情况下,让单链表逆置有很多方法,其中一个就是用三个指针实现单链表的逆置。
首先我们要定义一个student结构体,里面包括了名字,数字,以及指向下一个的指针。
1 typedef struct student{ 2 char name[MAX]; 3 int numb; 4 struct student *pNext; 5 }NODE,*PNODE;
然后在main函数里面建立我们的逆置函数,这里使用OPP来表示逆置单链表函数,在OPP函数内声明三个指针
1 PNODE pFirst,pMid,pLast;
要用三个指针来实现单链表的逆置,主要思路是这样:
假设有 A->B->C->D四个结构体,每一个都指向下一个,同样的有 pfirst,pmid,plast分别指向a,b,c三个结构体,然后断开a->b链接,使得b指向A,
此时变成了A<-B->C->D,三个指针同时向右移动一位,使得 pfirst,pmid,plast分别指向b,c,d三个结构体,再次执行同样的操作,此时链表变成了A<-B<-C->D,以此内推。
就可以写出逆置函数:
PNODE opp(PNODE pList){ PNODE pFirst,pMid,pLast;//申明三个指针 if(!pList||pList==NULL)//如果链表不存在或者不足两个,则直接退出 return(0); pFirst=pList;//让第一个指针指向链表 pMid=pFirst->pNext;//第二个指针指向链表的第二位 pFirst->pNext=NULL;//断开第一位和第二位的链接 pLast=pMid->pNext;//第三个指针指向第三位 pMid->pNext=pFirst;//使得第一二位反转
//要记住首先要给把第二个链表反转了,然后再用循环做接下来的
while(pLast){ //循环一次内推 pFirst=pMid; pMid=pLast; pLast=pMid->pNext; pMid->pNext=pFirst; } return(pMid);//最后返回mid的值,pLAST是NULL }
附上完整源代码:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #define MAX 100 5 typedef struct student{ 6 char name[MAX]; 7 int numb; 8 struct student *pNext; 9 }NODE,*PNODE; 10 PNODE crateList(); 11 PNODE opp(PNODE pList); 12 void traverseList(PNODE pList); 13 int main(void){ 14 PNODE pList; 15 pList=crateList(); 16 traverseList(pList); 17 pList=opp(pList); 18 traverseList(pList); 19 return(0); 20 } 21 PNODE crateList(){ 22 PNODE pHead=NULL,pCurrent,pPre; 23 char input[MAX]; 24 puts("enter the name"); 25 while(gets(input)!=NULL&&input[0]!='\0'){ 26 pCurrent=(PNODE)malloc(sizeof(NODE)); 27 if(pCurrent==NULL) 28 return(0); 29 if(pHead==NULL) 30 pHead=pCurrent; 31 else 32 pPre->pNext=pCurrent; 33 pCurrent->pNext=NULL; 34 strcpy(pCurrent->name,input); 35 puts("enter the number:"); 36 scanf("%d",&pCurrent->numb); 37 pPre=pCurrent; 38 puts("enter the next one or enter to leave"); 39 while(getchar()!='\n') 40 continue; 41 } 42 return(pHead); 43 } 44 void traverseList(PNODE pList){ 45 PNODE pCurrent; 46 pCurrent=pList; 47 if(pCurrent==NULL) 48 puts("no data enter!"); 49 else 50 while(pCurrent!=NULL){ 51 printf("the name is %s,and number is %d\n",pCurrent->name,pCurrent->numb); 52 pCurrent=pCurrent->pNext; 53 } 54 } 55 56 PNODE opp(PNODE pList){ 57 PNODE pFirst,pMid,pLast; 58 if(!pList||pList==NULL) 59 return(0); 60 pFirst=pList; 61 pMid=pFirst->pNext; 62 pFirst->pNext=NULL; 63 pLast=pMid->pNext; 64 pMid->pNext=pFirst; 65 while(pLast){ 66 pFirst=pMid; 67 pMid=pLast; 68 pLast=pMid->pNext; 69 pMid->pNext=pFirst; 70 } 71 return(pMid); 72 }