|
1鱼币
要求:删除循环链表的前驱
输出:2
3
以下是源代码:- #include<iostream>
- using namespace std;
- struct node{
- int data;
- node* next;
- };
- int main(){
- node a,b,c;
- a.data = 1; //建立具有3个结点,数据域值为1,2,3的单循环链表
- a.next = &b;
- b.data = 2;
- b.next = &c;
- c.data = 3;
- c.next = &a;
- node* p = &b;
- node* q = p;
- while(q->next->next != p){ //删除p结点的前驱
- q->next ->next = p;
- }
- q->next = p;
-
- q = p;
- cout<<q->data<<endl; //输出当前结点
- while(q->next!= p){ //遍历循环链表,输出其余结点
复制代码 只有while里的是自己的代码。不知道哪里错了。不能正确输出。
- #include<iostream>
- using namespace std;
- struct node{
- int data;
- node* next;
- };
- int main(){
- node a,b,c;
- a.data = 1; //建立具有3个结点,数据域值为1,2,3的单循环链表
- a.next = &b;
- b.data = 2;
- b.next = &c;
- c.data = 3;
- c.next = &a;
- node* p = &b;
- node* q = p;
- node* pre = q;
-
- //查找循环节点并断掉循环
- while(p != NULL && q != NULL)
- { if(p != NULL)
- {
- p = p->next;
- }
- if(p != NULL)
- {
- p = p->next;
- }
-
- pre = q;
- if(q != NULL)
- {
- q = q->next;
- }
-
- //找到循环节点,端掉循环
- if(p == q)
- {
- pre->next = NULL;
- break;
- }
- }
-
- //删除尾节点
- do
- {
- pre = p;
- p = p->next;
- if(p->next == NULL)
- {
- pre->next = NULL;
- break;
- }
- }while(true);
-
- cout<<q->data<<endl; //输出当前结点
- while(q != NULL)
- { //遍历循环链表,输出其余结点
- cout << q->data;
- q = q->next;
- }
- return 0;
- }
复制代码
|
|