单链表——单链表的逆转
来源:互联网 发布:单片机应用设计实例 编辑:程序博客网 时间:2024/06/06 14:10
最早据说是微软的一道题目,就是给出一个单链表和一个整数K,按照每K个个顺序进行逆转
废话不多说,看函数代码
//单链表的逆转,每k个逆转一下子PtrToNode Reverse(PtrToNode h,int K){int cnt=0;int len=length(h);PtrToNode newNode;PtrToNode oldNode;int i;PtrToNode tmp=NULL;PtrToNode tmphead=NULL;while(cnt+K<=len){cnt+=K;i=1;if(cnt==K){newNode=h->Next;oldNode=newNode->Next;while(i<K){tmp=oldNode->Next; oldNode->Next=newNode; newNode=oldNode; oldNode=tmp; i++; }}else{newNode=tmphead->Next;oldNode=newNode->Next;while(i<K){tmp=oldNode->Next; oldNode->Next=newNode; newNode=oldNode; oldNode=tmp; i++; }}if(cnt==K){tmphead=h->Next;//表示上面上一段序列里的最后h->Next->Next=oldNode; h->Next=newNode;}else{tmphead->Next->Next=oldNode; tmphead->Next=newNode;for(int j=0;j<K;j++)tmphead=tmphead->Next;}}return h;};
以上是最重要的一段代码
其示意图如上图所示
下面来看执行结果
哈哈哈,没毛病
下面上完整代码
#include <stdio.h> #include <stdlib.h> typedef struct Node *PtrToNode; struct Node { int Data; PtrToNode Next; }; //读入链表的函数PtrToNode Read();//打印链表的函数void Print( PtrToNode L );//单链表的逆转,每k个逆转一下子PtrToNode Reverse(PtrToNode h,int K);//求表长 int length(PtrToNode ptrl); int main() { for(int i=0;i<3;i++){ printf("请输入第%d/3组数据:\n",i+1); PtrToNode L1; L1 = Read(); int K;printf("请输入K:\n");scanf("%d",&K);Reverse(L1,K);Print(L1);printf("\n");}system("pause"); return 0; } PtrToNode Read() { int len = 0; int num = 0; PtrToNode h = NULL; PtrToNode last = NULL; h = ( PtrToNode )malloc( sizeof( struct Node ) );//建立头结点 h->Next = NULL; last = h; scanf( "%d",&len ); while(len){ scanf( "%d",&num ); PtrToNode node = ( PtrToNode )malloc( sizeof( struct Node ) ); node->Data = num; node->Next = NULL; last->Next = node; last = node; len--; } return h; } void Print( PtrToNode L ) { L=L->Next; if(L==NULL){ printf("NULL\n"); return; } while(L!=NULL){ printf("%d ",L->Data); L=L->Next; } putchar('\n'); };//求表长 int length(PtrToNode ptrl){ PtrToNode p=ptrl; int j=0; while(p){ p=p->Next; j++; } return j-1; }; //单链表的逆转,每k个逆转一下子PtrToNode Reverse(PtrToNode h,int K){int cnt=0;int len=length(h);PtrToNode newNode;PtrToNode oldNode;int i;PtrToNode tmp=NULL;PtrToNode tmphead=NULL;while(cnt+K<=len){cnt+=K;i=1;if(cnt==K){newNode=h->Next;oldNode=newNode->Next;while(i<K){tmp=oldNode->Next; oldNode->Next=newNode; newNode=oldNode; oldNode=tmp; i++; }}else{newNode=tmphead->Next;oldNode=newNode->Next;while(i<K){tmp=oldNode->Next; oldNode->Next=newNode; newNode=oldNode; oldNode=tmp; i++; }}if(cnt==K){tmphead=h->Next;//表示上面上一段序列里的最后h->Next->Next=oldNode; h->Next=newNode;}else{tmphead->Next->Next=oldNode; tmphead->Next=newNode;for(int j=0;j<K;j++)tmphead=tmphead->Next;}}return h;};
0 0