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++和數據結構,有錯誤請盡管指出,感激不盡!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM