线性表基本维护[ACM]

本文介绍如何使用C++创建动态链表,包括添加、移动、删除节点和打印链表元素的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 #include "iostream"
 2 #include "string"
 3 using namespace std;
 4 
 5 typedef struct node{
 6     string data;
 7     struct node *next;
 8     node(string str){
 9         data=str;
10         next=NULL;
11     }
12 
13 }Node;
14 
15 
16     Node *head=new node("hfirst");
17     Node *back=new node("bfirst");
18     Node *current=NULL;
19     Node *pre=head;
20 
21 
22 void add(string str){
23     Node *temp;
24     if(back->data=="bfirst")
25         temp=new Node(str);
26     else{
27         temp=back->next;
28         back->next=temp->next;
29         temp->data=str;
30         temp->next=NULL;
31     }
32     temp->next=head->next;
33     head->next=temp;
34     current=temp;
35 }
36 
37 void move(int p){
38     int i=0;
39     for(;i<p;i++){
40         pre=current;
41         if(current==NULL){
42             cout<<"worng!!!"<<endl;
43             current=head->next;
44             pre=head;
45             break;
46         }
47         else
48             current=current->next;
49     }
50 
51 }
52 
53 void del(int i){
54     Node *temp=current;
55     Node*tp;
56     while(i!=0&&current!=NULL){
57         tp=current;
58         current=current->next;
59         i--;
60     }
61     if(current==NULL){
62         
63         back->next=pre->next;
64         pre->next=NULL;
65         pre=head;
66         current=head->next;
67     }
68     else{
69         pre->next=current;
70         tp->next=NULL;
71         temp->next=back->next;
72         back->next=temp;
73     }
74     
75 }
76 void _print(){
77     cout<<current->data;
78 }
79 
80 
81 void main(){
82     string choice,str;
83     int i;
84     while(1){
85     cin>>choice;
86         if (choice==("ADD")){cin>>str;add(str);}
87         if (choice==("MOVE")){cin>>i;move(i);}
88         if (choice==("DEL")){cin>>i;del(i);}
89         if (choice==("PRINT"))_print();
90     }
91     getchar();
92 }

 

转载于:https://www.cnblogs.com/593213556wuyubao/p/3731418.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值