思路:
头插法建立一个新表。
*表头为first就是链表的第一个结点,无论这个单链表带不带头结点。
代码:
void reverse(LNode *first){//不妨令链表带头结点
LNode *p=first->next;
LNode *r=first;
first->next=NULL;
while(p){
r=p->next;
p->next=first->next;
first->next=p;
p=r;
}
}
测试:
//引入基本依赖库
#include<stdio.h>
#include <stdlib.h>
#include<math.h> //数学函数,求平方根、三角函数、对数函数、指数函数...
//定义常量 MAXSIZE
#define MAXSIZE 15
//用于使用c++的输出语句
#include<iostream>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode;
void createList(LNode *&L,int arr[],int length);
void printList(LNode *L);
void reverse(LNode *first);
void main(){
int a[]={1,3,5,7,9};
LNode *L1= new LNode();
L1->next=NULL;
createList(L1,a,5);
printList(L1);
cout<<endl;
reverse(L1);
printList(L1);
}
void reverse(LNode *first){//不妨令链表带头结点
LNode *p=first->next;
LNode *q=p->next;
first->next=NULL;
while(p){
p->next=first->next;
first->next=p;
p=q;
if(q)
q=q->next;
}
}
void createList(LNode *&L,int arr[],int length){
LNode *q=L;//q指向末尾结点
for(int i=0;i<length;i++){
LNode *node=new LNode();//创建一个新结点
node->data=arr[i];//将数组元素的值放入新创建的结点中
q->next=node;//将新结点接到链表后面
q=q->next;//将q后移到末端
}
q->next=NULL;//这是一个好习惯
}
void printList(LNode *L){
LNode *p=L;//p为循环遍历指针
while(p->next){
cout<<p->next->data<<"\t";
p=p->next;
}
}
本文介绍了如何设计一个算法,通过一次遍历将一个以first为表头的单链表逆序。采用头插法建立新的逆序链表,详细说明了思路和实现代码,并提供了测试用例。

被折叠的 条评论
为什么被折叠?



