1.有一个单链表的第一个节点指针为head,编写一个函数将该单链表逆置,即最后一个节点编程第一个节点,原来倒数第二个节点变成第二个节点,如此等等,在逆置中不能建立新的单链表。这里有两种方法,1、第一种是换数,即指针不变,只是用temp做中间变量,用temp=a;a=b;b=temp;形式把数换了。2、第二种时把指针换为逆向指针。
实现:
# include<iostream>
# include "stdio.h"
# include "stdlib.h"
# include "malloc.h"
using namespace std;
typedef int elemtype;
typedef struct linknode
{
elemtype data;
struct linknode* next;
}nodetype,*linklist;
nodetype* create();
nodetype* invert(nodetype* h);
nodetype* find(nodetype* h,int i);
void output(nodetype* h);
int len(nodetype* h);
int main()
{
nodetype* head;
head=create();
output(head);
invert(head);
output(head);
return 0;
}
nodetype* create()
{
nodetype*s,* la,*p;
int x;
cout << "输入x值,当x≠0时候,继续输入,0停止。" << endl;
cin >> x;
la=(nodetype *)malloc(sizeof(nodetype));
s=p=la;
while(x!=0)
{
s=(nodetype*)malloc(sizeof(nodetype));
s->data=x;
p->next=s;
p=s;
cin >> x;
}
cout << "结束" << endl;
p->next=NULL;
return la;
}
nodetype* invert(nodetype* h)
{
int i,length,temp;
nodetype* p,* q;
length=len(h);
for(i=1;i<(1+length)/2;i++)
{
p=find(h,i);
q=find(h,length+1-i);
temp=p->data;
p->data=q->data;
q->data=temp;
}
return h;
}
nodetype* find(nodetype* h,int i)
{
int j;
nodetype* p;
p=h;
for(j=0;j<i;j++)
p=p->next;
return p;
}
int len(nodetype* h)
{
int i=0;
nodetype* p;
p=h;
while(p->next!=0)
{
i++;
p=p->next;
}
return i;
}
void output(nodetype* h)
{
nodetype* q;
q=h->next;
while(q!=NULL)
{
cout << q->data << " ";
q=q->next;
}
cout << "end" << endl;
}
我在编写输出函数时候又犯错误,错误示例如下:
void output(nodetype* h)
{
nodetype* p;
p=h;
while(p->next!=NULL)
{
cout << p->data << " " ;
p=p->next;
}
}
第二种如图(带头结点)
程序:
# include<iostream>
# include "stdio.h"
# include "stdlib.h"
# include "malloc.h"
using namespace std;
typedef int elemtype;
typedef struct linknode{
elemtype data;
struct linknode* next;
}nodetype,*linklist;
nodetype* create();
void output(nodetype* h);
nodetype* invert(nodetype* h);
int len(nodetype *h);
void main()
{
nodetype* head,*h;
head=create();
output(head);
cout << "逆置后" << endl;
head=invert(head);
output(head);
}
nodetype* create()
{
nodetype *r,*s,*la;
int x;
cout <<"输入0表示结束。" << endl;
cout << "输入结点值:" << endl;
cin >> x;
la=(linklist)malloc(sizeof(linknode));
r=s=la;
while(x!=0)
{
s=(linklist)malloc(sizeof(linknode));
s->data=x;
r->next=s;
r=s;
cout <<"输入结点值:" << endl;
cin >> x;
}
r->next=NULL;
return la;
}
void output(nodetype* h)
{
nodetype* q;
q=h->next;
while(q!=NULL)
{
cout << q->data << " ";
q=q->next;
}
}
int len(nodetype *h)
{
int i=0;
nodetype* p;
p=h;
while(p->next!=NULL)
{
p=p->next;
i++;
}
return i;
}
nodetype* invert(nodetype* h)
{
nodetype* p,* q,* r,*ha;
if(len(h)<=1)
{
cout << "逆置至少两个结点" << endl;
}
else
p=h->next;
q=p->next;
{
while(q->next!=NULL)
{
r=q->next;
q->next=p;
p=q;
q=r;
}
q->next=p;
}
h->next->next=NULL;
free(h);
ha=(nodetype*)malloc(sizeof(nodetype));
ha->next=q;
return ha;
}