C++中实现链表的删除和颠倒

MFC工程中关于链表的操作

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

关于eraseValue函数的定义:

 1 template <typename T>
 2 void eraseValue(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<n;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     eraseValue(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 <typename T>
 2 void reverse(node*first,const T&n)
 3 {    
 4     node *front=NULL;
 5     for(int i=0;i<n-1;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 }

 

初学c++和数据结构,有错误请尽管指出,感激不尽!!

posted @ 2014-10-19 12:10  verlen  阅读(3419)  评论(0编辑  收藏  举报