链表的插入与删除

来源:互联网 发布:led视频制作软件 编辑:程序博客网 时间:2024/06/06 07:20

                                          链表的插入与删除

<span style="font-size:18px;color:#ff0000;">思路:</span>
<span style="font-size:18px;color:#ff0000;">      上学期自学了指针,不知道是没理解透彻,还是其它原因。但是过了两个月后,感觉写起来好像切菜一样,感觉容易了很多。就像大话数据结构里的作者说的,学会了就是这点儿事。</span>
#include <iostream>using namespace std;struct S{int a;S *next;}*p,*head,*q;int i;void NewRoom(int n)//申请动态空间{head = new S;head->next = NULL;//head=NULL会错,我认为是head复制了NULL的地址给自己所以错了p=head;for (i=0;i<n;++i){q = new S;cin >> q->a;head->next = q;head = q;}head->next=NULL;}void insert(int k,int t)//插入元素{head = p;while (k--){head=head->next;}q = new S ;q->a = t;q->next = head->next;head->next = q;}void Delete(int k)//删除元素{head = p;while (k--){q=head;head = head->next;}q->next = head->next;}void Cout()//输出{p=p->next;while (p){head=p;cout << p->a << " " ;p=p->next;delete head;}cout << endl;}int main(){int k,n,t;while (cin >> n){NewRoom(n);cin >> k >> t;//插入一个数,k为位置,t为数值insert(k,t);/*cin >> k;Delete(k);*/Cout();}return 0;}

0 0
原创粉丝点击