中易网

请用C++写一个函数,这个函数使单链表方向逆转

答案:3  悬赏:40  
解决时间 2021-02-03 06:26
是单链表方向逆转
用指针操作。。。
用while循环操作
如果用C++的类和对象表示,我再追加50分
最佳答案
我这个程序行不行?

#include <stdio.h>
#include <stdlib.h>

typedef struct _Node
{
struct _Node *next;
int val;
} Node;

void reverseNodes(Node *node)
{
if (node->next == NULL)
{
return;
}
else
{
reverseNodes(node->next);
node->next->next = node;
}
}

void reverseList(Node *node)
{
reverseNodes(node);
node->next = NULL;
}

void printList(Node *node)
{
while (node)
{
printf("%d-->", node->val);
node = node->next;
}
printf("end\n");
}

int main(void)
{
Node n1, n2, n3, n4;

n1.next = &n2;
n1.val = 1;

n2.next = &n3;
n2.val = 2;

n3.next = &n4;
n3.val = 3;

n4.next = NULL;
n4.val = 4;

reverseList(&n1);

printList(&n4);

return 0;
}

你是要折腾我吧?

#include <stdio.h>
#include <stdlib.h>

typedef struct _Node
{
struct _Node *next;
int val;
} Node;

void reverseList(Node *head)
{
Node *node = head;
int i, num = 0;
Node **array;

while (node)
{
node = node->next;
num++;
}

array = (Node **)malloc(sizeof(Node *) * num);

i = 0;
node = head;
while (node)
{
array[i] = node;
node = node->next;
i++;
}

for (i = 0; i < num; i++)
{
if (i == 0)
{
array[i]->next = NULL;
}
else
{
array[i]->next = array[i - 1];
}
}
}

void printList(Node *node)
{
while (node)
{
printf("%d-->", node->val);
node = node->next;
}
printf("end\n");
}

int main(void)
{
Node n1, n2, n3, n4;

n1.next = &n2;
n1.val = 1;

n2.next = &n3;
n2.val = 2;

n3.next = &n4;
n3.val = 3;

n4.next = NULL;
n4.val = 4;

reverseList(&n1);

printList(&n4);

return 0;
}
全部回答
主函数中i.linklist(g[10],5);改为i.linklist(g,5);数组调用时用数组名
#include<iostream> using namespace std; struct LNode { int num; LNode *next; }; LNode* func(LNode *head) { LNode *pf,*pm,*pl; pf=head; if(pf) if(pm=pf->next) { while(pm) { pl=pm->next; pm->next=pf; pf=pm; pm=pl; } head->next=NULL; } return pf; } void main() { LNode *t,*head=NULL,*pos; for(int i=0;i<5;++i) { t=new LNode; cin>>t->num; if(!head){head=t;pos=head;} else {pos->next=t;pos=t;} } pos->next=NULL; pos=head; while(pos) { cout<<pos->num<<" "; pos=pos->next; } cout<<endl; head=func(head); pos=head; while(pos) { cout<<pos->num<<" "; pos=pos->next; } cout<<endl; } //////////////// 下面这个是递归函数,用这个函数替换上面的func()函数即可运行,其它地方不用改 LNode* func(LNode *head) { LNode *p; if(head) if(head->next) { p=func(head->next); head->next->next = head; head->next=NULL; return p; } else return head; }
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
藤生 野果 牛浩卵 乌栏扒
小三家子村在什么地方啊,我要过去处理事情
这双鸿星尔克的鞋子货号是多少啊?就是广告上
小狗的腿崴了可以吃人的药用什么?
用料理机时用搅拌杯时过滤网要拿下来吗
王大汉市场怎么去啊,有知道地址的么
明亮眼镜NO.2地址在哪,我要去那里办事
征集温馨的店名
有种你爱我哪首歌里面有这个词
关于科学奉献精神的成语10个
房产证上有我和爸爸的名字,是否我也拥有房子
绿色光照射肥皂薄膜产生的干涉条纹间距与黄色
老码头休闲吧地址在什么地方,想过去办事
旅森男装天猫旗舰店怎么找不到
MBA考试要准备多久?
推荐资讯
宝马minicooper空调面板在哪里?
王者荣耀什么坦克最厉害?
8号川色缘在什么地方啊,我要过去处理事情
山西介休到河南焦作的火车
服务生和勤杂工有啥区别和传菜员
物理中实际电压大于额定电压为什么就能确定功
SERENE HOUSE的车载香氛一般能用多长时间?
高职专科毕业证是不是大专的意思
300020 这支股票 怎么样 求解?
请帮忙翻译两个数字,谢谢!
求类似于重生之我能升级的小说 要完结的
中国人在韩国处境怎么样?
手机登qq时,显示手机磁盘不足,清理后重新登
刺客的套装怎么选啊?