Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

c++ - How to create a function that act as 'stack.push(Node* temp)' in a linked list?

I want to create a function that reverses the linked list by using a stack model but not using class 'stack'. I am stuck in creating a function stack.push(Node temp)*;

So how can I create a function that acts as stack.push(Node* temp)?

For example, if I use class stack, line5 S.Push(temp) accepts the Node* temp.

void Reverse() {
stack <Node*> S;
Node*temp = Head;
while(temp != NULL){
 S.push(temp);
 temp = temp->next;
}

temp = S.top();
Head = temp;
S.pop();

while(!S.empty()){
 temp->next = S.top();
 S.pop();
 temp = temp->next;
}
temp->next = NULL;

}

What I created:

class stacks{
 public: 
 //constructor 
 stacks(){
   Node* top = NULL;
  }

  void Push(Node* x){
     struct Node* y;
     if(y==NULL){
        y = x;
     }
     else
     while(y->next == NULL){
        y = y->next;
     }
     y->next = x;
 }  

 void Reverse() {
   stacks tempo;
   //top is already set as global variable
   Node* temp = top;

   while(temp != NULL){
     tempo.Push(temp);
     temp = temp->next;
   }

   top=tempo.Top();
   tempo.Pop();
   temp->next = tempo.Top();
   while(!tempo.empty())
  {
   temp = temp->next;
   tempo.Pop();
   temp->next = tempo.Top();
   }
   temp->next = NULL;
   }
question from:https://stackoverflow.com/questions/65679857/how-to-create-a-function-that-act-as-stack-pushnode-temp-in-a-linked-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...