链表反转(倒置) 第2次 非递归 C++

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 北京交通大学 2007-3-30
#include <iostream>
using namespace std;
struct LNode
{
int data;
struct LNode *next;
};
class Link
{
public:
Link():m_Len(0),m_head(0){};
Link(int Len);
Print();
Reverse();
private:
LNode *m_head;
int m_Len;
};
Link::Link(int Len)
{
int i;
LNode *ptr;
m_head=ptr=new LNode;
for(i=1;i<=Len;i++)
{
cin>>ptr->data;
if(i<Len)
{
ptr->next=new LNode;
ptr=ptr->next;
}
}
ptr->next=NULL;
}
Link::Print()
{
LNode *ptr=m_head;
while(ptr!=NULL)
{
cout<<ptr->data<<endl;
ptr=ptr->next;
}
}
Link::Reverse()
{
LNode *ptr1=m_head,*ptr2=ptr1->next,*ptr3;
ptr1->next=NULL;
while(ptr2!=NULL)
{
ptr3=ptr2->next;
ptr2->next=ptr1;
ptr1=ptr2;
ptr2=ptr3;
}
m_head=ptr1;
}
int main()
{
Link l(5);
l.Print();
l.Reverse();
l.Print();
return 0;
}
// 北京交通大学 2007-3-30 #include <iostream> using namespace std; struct LNode { int data; struct LNode *next; }; class Link { public: Link():m_Len(0),m_head(0){}; Link(int Len); Print(); Reverse(); private: LNode *m_head; int m_Len; }; Link::Link(int Len) { int i; LNode *ptr; m_head=ptr=new LNode; for(i=1;i<=Len;i++) { cin>>ptr->data; if(i<Len) { ptr->next=new LNode; ptr=ptr->next; } } ptr->next=NULL; } Link::Print() { LNode *ptr=m_head; while(ptr!=NULL) { cout<<ptr->data<<endl; ptr=ptr->next; } } Link::Reverse() { LNode *ptr1=m_head,*ptr2=ptr1->next,*ptr3; ptr1->next=NULL; while(ptr2!=NULL) { ptr3=ptr2->next; ptr2->next=ptr1; ptr1=ptr2; ptr2=ptr3; } m_head=ptr1; } int main() { Link l(5); l.Print(); l.Reverse(); l.Print(); return 0; }
// 北京交通大学 2007-3-30

#include <iostream>
using namespace std;
struct LNode
{
 int data;
 struct LNode *next;
};

class Link
{
public:
 Link():m_Len(0),m_head(0){};
 Link(int Len);
 Print();
 Reverse();
private:
 LNode *m_head;
 int m_Len;
};

Link::Link(int Len)
{
 int i;
 LNode *ptr;
 m_head=ptr=new LNode;
 for(i=1;i<=Len;i++)
 {
  cin>>ptr->data;
  if(i<Len)
  {
   ptr->next=new LNode;
   ptr=ptr->next;
  }
 }
 ptr->next=NULL;

}

Link::Print()
{
 LNode *ptr=m_head;
 while(ptr!=NULL)
 {
  cout<<ptr->data<<endl;
  ptr=ptr->next;
 }
}

Link::Reverse()
{
 LNode *ptr1=m_head,*ptr2=ptr1->next,*ptr3;
 ptr1->next=NULL;
 while(ptr2!=NULL)
 {
  ptr3=ptr2->next;
  ptr2->next=ptr1;
  ptr1=ptr2;
  ptr2=ptr3;
 }
 
 m_head=ptr1;
}

int main()
{
 Link l(5);
 l.Print();
 l.Reverse();
 l.Print();
 return 0;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *