0$房天下问答|c++程序设计$https://m.fang.com/ask/ask_1017303.html$https://static.soufunimg.com/common_m/m_public/201511/images/asksharedefault.png
packc/pages/ask/detail/detail?askid=1017303
-
c++程序设计
求大家帮忙写一个“逆转”给定链表的函数~~思路大致就是要访问遍整个链表的结点~~每访问一个结点~~就把这个结点作为整个链表的第一个结点~~这样等访问完链表的最后的一个结点时~~整个链表就被逆转过来了~~//建立一个链表~~元素之依次为从键盘输入的正整数(以输入一个非整数为结束),然后先输出为逆转前的链表中的各元素值~~之后再输出逆转后链表中的各元素值~~#include<iostream>#include<iomanip>using namespace std;struct Node{int d; Node *next;};int main(){int x;cout<<"请为第一个链表Node输入数据:"Node *head,*p,*q; head=NULL; q=NULL; cin>>x; while(x>0) {p=new Node; p->d=x; p->next=NULL; if(head==NULL) head=p; else q->next=p; q=p; cin>>x; }p=head;while(p!=NULL) {cout<<setw(5)<<(p->d); q=p; p=p->next; delete q; }cout<<endl; //中间这个逆转链表的程序我不会写~~//不知道逆转后再输出这个链表的程序是不是也这么写如下~~要是需要改的话~~不知道怎么改~~p=head;while(p!=NULL) {cout<<setw(5)<<(p->d); q=p; p=p->next; delete q; }cout<<endl;return 0;} 我现在真是既着急又纠结~~~~求各位可怜我一下~~帮帮忙教教我这个逆转的函数怎么写~~真的是辛苦各位感激不尽了~~~
更多
提问者:tommypeng
发布于2010-11-05
共1个回答
-
-
-
jiangnanqianqiu
丨Lv 0
#include <iostream>using namespace std;struct Node{ int data; Node * next;};Node * Create_List(){ Node * head=new Node;//头结点 Node * rear=head; head->next=NULL; Node * s; int x; cin>>x; while(x>0) { s=new Node ; s->data=x; s->next=NULL; rear->next=s; rear=s; cin>>x; } return head;}void Print_List(Node * head){ Node * p=head->next; while(p!=NULL) { cout<<p->data<<" "; p=p->next; }}void Reverse_List(Node * head){ if(head->next==NULL) return ; Node * p,*q; p=head->next;//第一个元素 q=head->next; while(q->next!=NULL) q=q->next;//最后一个元素 int temp;//交换两个数用的中间变量 while(p!=q&&q->next!=p) { temp=p->data; p->data=q->data; q->data=temp; p=p->next;//指向下一个元素 Node * s=head; while(s->next!=q) s=s->next; q=s;//指向前一个元素 }} int main(int argv,char * argc[]){ Node * head; head=Create_List(); cout<<"逆置前单链表元素:"<<endl; Print_List(head); Reverse_List(head); cout<<"\n逆置后单链表元素:"<<endl; Print_List(head); cout<<endl; system("pause"); return 0;} //我用的是DEV C++编译器环境
免责声明:问答内容均来源于互联网用户,房天下对其内容不负责任,如有版权或其他问题可以联系房天下进行删除。

关注成功