设为首页 加入收藏

TOP

C++中实现链表的删除和颠倒
2015-07-20 17:26:02 来源: 作者: 【 】 浏览:4
Tags:实现 删除 颠倒
1.对于给定的整数n,编写算法删除链表中第n个节点,该链表的第一个节点由first指向。
?
?
?
由于C++中没有关于node的标准头文件,要先手动定义node类,此处只定义了简单的data和next指针以及析构函数部分的内容:
?
复制代码
1 class node ?
2 {
3 public:
4 ? ? node(const int &in,node *nextnode = NULL);
5 ? ? virtual ~node();
6 ? ? node*next;
7 ? ? int data;
8?
9 };
复制代码
#include"node.h"之后就可以定义节点了。
?
1 node *p1,*p2,*p3;
2 ? ? p1=new node(1);
3 ? ? p2=new node(2,p1);
4 ? ? p3=new node(3,p2);
此处定义出的链表 图示如下:
?
p3-->p2-->p1
?
3 -->2 -->1
?
关于eraseva lue函数的定义:
?
复制代码
?1 template
?2 void eraseva lue(node*first,const T&n)
?3 {
?4 ? ? node *curr=first,*pre=NULL;
?5 ? ? if(n==1)
?6 ? ? {
?7 ? ? ? ? first=first->next;
?8 ? ? ? ? delete curr;
?9 ? ? }
10 ? ? else {for(int i=1;i
11 ? ? {
12 ? ? ? ? pre=curr;
13 ? ? ? ? curr=curr->next;
14 ? ? }
15?
16 ? ? ? ? pre->next=curr->next;
17 ? ? ? ? delete curr;}
18?
19 }
复制代码
函数调用及输出(改):
?
当n=1时会报错,有待解决。
?
复制代码
?1 ? ? node *cur=p3;
?2 ? ? eraseva lue(p3,2);
?3 ? ? CString temp,str;
?4 ? ? while(cur->data!=NULL)
?5 ? ? {
?6 ? ? ? ? temp.Format("%d ",cur->data);
?7 ? ? ? ? str+=temp;
?8 ? ? ? ? cur=cur->next;
?9 ? ? }
10 ? ? AfxMessageBox(str);
复制代码
?
?
?
?
?
?
2.编写一个算法来颠倒链表,不要复制链表元素,而是重置链接和指针,使得first指向原来的最后一个节点,且节点之间所有链接都反向。
?
未经输出测试:
?
复制代码
?1 template
?2 void reverse(node*first,const T&n)
?3 { ? ?
?4 ? ? node *front=NULL;
?5 ? ? for(int i=0;i
?6 ? ? { ? ?
?7 ? ? ? ? node *curr=first,*pre=NULL; ? ? ? ?
?8 ? ? ? ? while(curr->next!=NULL)
?9 ? ? ? ? {
10 ? ? ? ? ? ? pre=curr;
11 ? ? ? ? ? ? curr=curr->next;
12 ? ? ? ??
13 ? ? ? ? }
14 ? ? ? ? if(i==0&&curr->next==NULL) front=curr;
15 ? ? ? ? pre->next=NULL;
16 ? ? ? ? curr->next=pre;
17 ? ? }
18 ? ? if(i=n-1) first->next=front;
19 ? ? front=first;
20 }
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu 1041(Computer Transformati.. 下一篇POJ 1742 Coins(dp)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·微服务 Spring Boot (2025-12-26 18:20:10)
·如何调整 Redis 内存 (2025-12-26 18:20:07)
·MySQL 数据类型:从 (2025-12-26 18:20:03)
·Linux Shell脚本教程 (2025-12-26 17:51:10)
·Qt教程,Qt5编程入门 (2025-12-26 17:51:07)