您的位置:首页 > 健康 > 美食 > C++:用类实现链表,队列,栈

C++:用类实现链表,队列,栈

2024/12/23 6:31:06 来源:https://blog.csdn.net/2301_80311224/article/details/142306031  浏览:    关键词:C++:用类实现链表,队列,栈

用类实现链表:

#include<iostream>
using namespace std;class List
{struct Node{int Nval;Node* pNext;};
private:Node* pHead = NULL;Node* pEnd = NULL;
public:void AddNode(int n);void DelNode(int n);void walk();
};
void List::AddNode(int k)
{Node* ptemp = new Node;ptemp->Nval = k;ptemp->pNext = NULL;if (NULL == pHead){pHead = ptemp;}else{pEnd->pNext = ptemp;}pEnd = ptemp;
}
void List::DelNode(int n)
{Node* pdel = NULL;if (pHead->Nval == n){pdel = pHead;pHead = pHead->pNext;free(pdel);pdel = NULL;return;}Node* pmark = pHead;while (pmark->pNext != NULL){if (pmark->pNext->Nval == n){pdel = pmark->pNext;pmark->pNext = pmark->pNext->pNext;free(pdel);pdel = NULL;if (pmark->pNext == NULL){pEnd = pmark;}return;}pmark = pmark->pNext;}
}
void List::walk()
{while (pHead != NULL){cout << pHead->Nval << endl;pHead = pHead->pNext;}
}int main()
{List list;list.AddNode(1);list.AddNode(2);list.AddNode(3);list.DelNode(1);list.DelNode(2);list.walk();return 0;
}

用类实现队列:

#include<iostream>
using namespace std;class Queue
{struct Node{int Nval;Node* pNext;};
private:Node* pHead = NULL;Node* pEnd = NULL;
public:void Push(int n);int pop();};
void Queue::Push(int n)
{Node* pTemp = new Node;pTemp->Nval = n;pTemp->pNext = NULL;if (pHead == NULL){pHead = pTemp;}else{pEnd->pNext = pTemp;}pEnd = pTemp;
}
int Queue::pop()
{if (pHead != NULL){Node* pdel = pHead;pHead = pHead->pNext;int n = pdel->Nval;free(pdel);pdel = NULL;if (NULL == pHead){pEnd = NULL;}return n;}return -1;
}int main()
{Queue yan;yan.Push(1);yan.Push(2);yan.Push(3);cout << yan.pop() << endl;cout << yan.pop() << endl;cout << yan.pop() << endl;return 0;
}

用类实现栈:

#include<iostream>
using namespace std;class List
{struct Node{int n;Node* pnext;};
private:Node* ptop = NULL;
public:void push(int n);int pop();
};
void List::push(int n)
{Node* ptemp = new Node;ptemp->n = n;ptemp->pnext = NULL;if (ptop != NULL){ptemp->pnext = ptop;ptop = ptemp;}else{ptop = ptemp;}
}
int List::pop()
{if (ptop != NULL){Node* pdel = ptop;ptop = ptop->pnext;int k = pdel->n;free(pdel);pdel = NULL;return k;}return -1;
}int main()
{List k;k.push(1);k.push(2);k.push(3);cout << k.pop()<< endl;cout << k.pop() << endl;cout << k.pop() << endl;return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com