Inserting a element in a singly circular linked list in sorted manner
我想创建一个程序,它以排序的方式将数据插入到单循环链表中(给定指向最后一个元素的指针)。
我已经编写了代码,尝试调试它,但实际上无法找到问题所在。
我得到的输出是
5
6 6
7
7 7
9 9 9
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
#include <iostream>
using namespace std; void displaylist(Node *l){ int main() |
让我们来看看
1
2 3 4 5 6 7 8 9 |
void displaylist(Node *l){
Node* last = l–>next; // points at first node. Sounds OK do{ cout<<l–>val<<""; // always print last node. Doesn’t seem like a good idea last = last–>next; //advance one node. Sounds OK }while(last–>next != l); // loop until the node after the next node is back to the last node // Looks past at least one node cout<<endl; } |
首先我们改变了一些标识符,以便它们更能描述它们真正代表的内容
1
2 3 4 5 6 7 8 |
void displaylist(Node *last){ // l is the last node
Node* current = last–>next; //current is a better name for the item we’re looking at do{ cout<<last–>val<<""; current = current–>next; }while(current–>next != last); cout<<endl; } |
现在我们通过打印出我们正在迭代的项目而不是一遍又一遍地打印第一个项目来开始修复问题。
1
2 3 4 5 6 7 8 |
void displaylist(Node *last){
Node* current = last–>next; do{ cout<<current–>val<<""; // print out the item we’re iterating current = current–>next; }while(current–>next != last); cout<<endl; } |
现在我们要做的是在下一个要打印的项目再次是第一个时停止,即
1
2 3 4 5 6 7 8 |
void displaylist(Node *last){
Node* current = last–>next; do{ cout<<current–>val<<""; current = current–>next; }while(current != last–>next); cout<<endl; } |
应该差不多了。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/268939.html