贴两个关于c++链表的代码
代码一是一个双向链表
#include <iostream>using namespace std;typedef struct PNODE { int m; struct PNODE *next; struct PNODE *PRevious;} node, *Pnode;int main(){ int n; cin >> n; Pnode PHead = new(node); Pnode PLast = new(node); PHead->next = PLast; PHead->previous = NULL; PLast->next = NULL; PLast->previous = PHead; Pnode PTail = PHead; for (int i = 0; i < n; i++) { Pnode PNew = new(node); cin >> PNew->m; PNew->previous = PTail; PNew->next = PTail->next; PTail->next = PNew; PNew->next->previous = PNew; PTail = PTail->next; } PTail = PLast->previous; while (PTail->previous != NULL) { cout << PTail->m << endl; PTail = PTail->previous; } return 0;}代码二是顺序表元素的比较和删除,题目如下
已知a、b和c三个递增有序的线性表,现在要求对a做如下操作:删除其中既即在b中出现又在c中出现的元素(注意同一表中的元素有可能重复)。
#include <iostream>using namespace std;typedef struct PNODE { int m; struct PNODE *next;}PNode, *Node;//这一块函数在写的时候调了好几次,个人认为可以加深对指针的理解void Input(Node *P, int n){ *P = new(PNode); Node PHead = *P; PHead->next = NULL; Node PTail = PHead; for (int i = 0; i < n; i++) { Node PNew = new(PNode); cin >> PNew->m; PNew->next = NULL; PTail->next = PNew; PTail = PNew; }}int main(){ int n, m, l; cin >> n >> m >> l; Node PNHead, PMHead, PLHead; Input(&PNHead, n); Input(&PMHead, m); Input(&PLHead, l); Node PNTail = PNHead; Node PMTail = PMHead; Node PLTail = PLHead; while (PNTail->next != NULL) { //这个地方&&前后不能颠倒,因为根据c++(c)语言编译器的特性从左向右判断,颠倒后就会报错 while (PMTail->next != NULL && PNTail->next->m > PMTail->next->m) PMTail = PMTail->next; while (PLTail->next != NULL && PNTail->next->m > PLTail->next->m) PLTail = PLTail->next; if (PMTail->next == NULL || PLTail->next == NULL) break; if (PNTail->next->m == PMTail->next->m && PNTail->next->m == PLTail->next->m) { Node P = PNTail->next; PNTail->next = P->next; //这个地方建议养成这个习惯,减少写大东西的时候不必要的内存泄露 delete(P); } else PNTail = PNTail->next; } PNTail = PNHead->next; while (PNTail != NULL) { cout << PNTail->m << endl; PNTail = PNTail->next; } return 0;}新闻热点
疑难解答
图片精选