今天上课所写的链表的头插入和头删除,考虑了各种异常处理。
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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
| #include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
/创建链表,并返回链表头指针head/
struct node *create()
{
struct node *head=NULL;
struct node *p;
p=(struct node*)malloc(sizeof(struct node));
p->data=95;
p->next=head;
head=p;
p=(struct node*)malloc(sizeof(struct node));
p->data=90;
p->next=head;
head=p;
return head;
}
/输出链表head/
void print(struct node *head)
{
struct node *p=head;
while(p!=NULL)
{
printf("%d\t",p->data); p=p->next; }
}
/将数据data插入到链表head中/
struct node *insert(struct node *head,int data)
{
struct node *p;
struct node q,s;
q=head;
while(q!=NULL&&q->data<data)
{
s=q; q=q->next; }
p=(struct node*)malloc(sizeof(struct node));
p->data=data;
if(q==head)
{
p->next=q; head=p; }
else
{
p->next=q; s->next=p; }
return head;
}
/删除链表head中的指定元素data/
struct node *deletePoint(struct node *head,int data)
{
struct node s,q;
q=head;
while(q!=NULL&&q->data!=data)
{
s=q; q=q->next; }
if(q==head)
{
head=q->next; }
else
{
s->next=q->next; }
free(q);
return head;
}
void main()
{
struct node *head;
head=create();
printf("head链表中的元素:");
print(head);
printf("\n");
head=insert(head,92);
printf("head链表中插入操作以后的元素:");
print(head);
printf("\n");
head=insert(head,87);
printf("head链表中插入操作以后的元素:");
print(head);
printf("\n");
head=insert(head,85);
printf("head链表中插入操作以后的元素:");
print(head);
printf("\n");
head=insert(head,100);
printf("head链表中插入操作以后的元素:");
print(head);
printf("\n");
head=deletePoint(head,87);
head=deletePoint(head,85);
head=deletePoint(head,100);
printf("head链表中删除操作以后的元素:");
print(head);
printf("\n");
}
|
这段时间太忙了,连女朋友都不能照顾到了,宝宝,和你说声对不起。