链表:女生节快乐

Posted by Cww97 on 2016-03-08

版权声明:本文为博主原创文章,未经博主允许不得转载。原文所在http://blog.csdn.net/cww97 https://blog.csdn.net/cww97/article/details/50823535
这里写图片描述

好久不写指针、、、代码能力大不如从前

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include<cstdio> 
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=233;
int cnt;
struct node{
int num;
struct node *next;
node(){num=0;next=NULL;}

node *build(node **head){
*head=new node;
puts("Tell me how many numbers");
puts("you want to put into the linklist");
int n;scanf("%d",&n);
printf("give me %d numbers\n",n);
int arr[N];cnt=n;
for (int i=1;i<=n;i++)scanf("%d",&arr[i]);
for (int i=n;i>=1;i--){//倒过来,前插法
node *p=new node;
p->num=arr[i];
p->next=(*head)->next;
(*head)->next=p;
}
return *head;
}

void insert(node *head){
int k=cnt+2;
while (k>cnt+1){
puts("tell me where do you want to insert");
scanf("%d",&k);
if (k>cnt)puts("too big,give me a smaller location");
}
puts("tell me which number");
int x;scanf("%d",&x);
node *p=(node*)malloc(sizeof(node));
node *q=(node*)malloc(sizeof(node));
p=head;
for (int i=1;i<k;i++) p=p->next;
q->next=p->next;
q->num=x;
p->next=q;
cnt++;
}

void deltee(node *head){
int k=cnt+1;
while (k>cnt){
puts("tell me which do you want to delete");
scanf("%d",&k);
if (k>cnt)puts("too big,give me a smaller location");
}
node *p=(node*)malloc(sizeof(node));
node *q=(node*)malloc(sizeof(node));
p=head;
for (int i=1;i<k;i++) p=p->next;
q=p->next;//q=即将删除的元素
p->next=q->next;
free(q);
}

void print(node* head){
node* t=head->next;
while (t!=NULL){
printf("%d ",t->num);
t=t->next;
}
puts("");
}
};

int solve(){
puts("Welcome");
char st[5];
struct node *head;
head=NULL;
while (scanf("%s",st)&&(st[0]!='q')){
if (st[0]=='b')head=head->build(&head);//建立
if (st[0]=='i')head->insert(head);//插入
if (st[0]=='d')head->deltee(head);//删除
if (st[0]=='s')head->print(head);//显示
}
return 0;
}

int main(){
return solve();
}

感谢【静静】的指导
这里写图片描述