题目,以录入三个学生的成绩,学号为目的,创建链表
(1)C语言(静态链表)
# include
struct Student
{
long int num;
float score;
struct Student * next;
};
int main()
{
struct Student s1, s2, s3, * head, *p;
s1.num = 10101; s1.score = 89.5;
s2.num = 10102; s2.score = 90;
s3.num = 10103; s3.score = 85;
head = &s1;
s1.next = &s2; s2.next = &s3; s3.next = NULL;
p = head;
do
{
printf("%ld %5.1f\n", p->num, p->score);
p = p->next;
}while(p != NULL);
printf("已打印完链表所有信息!\n");
return 0;
}
(2)C语言(动态链表)
# include
# include
# define LEN sizeof(struct Student)
struct Student
{
long num;
float score;
struct Student * next;
};
int n = 0;
struct Student * create(void)
{
struct Student *p1, *p2, *head;
p1 = p2 = (struct Student * )malloc(LEN);
printf("请输入学生信息:\n");
scanf("%d, %f", &p1->num, &p1->score);
head = NULL;
while(p1->num != 0)
{
n += 1;
if (n==1) head=p1;
else p2->next=p1;
p2 = p1;
p1 = (struct Student * )malloc(LEN);
printf("请输入学生信息\n");
scanf("%d, %f", &p1->num, &p1->score);
}
p2->next = NULL;
return head;
}
int main()
{
struct Student * h;
h = create();
printf("num == %ld\n, score == %5.1f\n", h->num, h->score);
return 0;
}
python实现
- 针对python的,我使用字典来实现
- 很有意思,对数据字段进行了 限制,并且增加了迭代器循环输出
- 也可以将 Node类进行改造为单例,这里我没有继续下去~
class BaseField():
def __init__(self, attrname):
self.attrname = attrname
def __get__(self, instance, owner):
return getattr(instance, self.attrname)
def __set__(self, instance, value):
setattr(instance, self.attrname, value)
def __delete__(self, instance):
raise Exception('can not delete email')
import re
class NumField(BaseField):
NUM_MOD = re.compile('^\d{4,6}$')
def __set__(self, instance, value):
if not self.NUM_MOD.match(value):
raise Exception('请输入有效格式学号!')
setattr(instance, self.attrname, value)
class ScoreField(BaseField):
def __set__(self, instance, value):
if not (0 <= value and value <= 100):
raise Exception('{}错误!成绩为 0-100,请重新输入!'.format(value))
setattr(instance, self.attrname, value)
class Node():
num = NumField("_num")
score = ScoreField("_score")
def __init__(self, num, score):
self.num = num
self.score = score
self.node = {
'num': '00001',
'score': 0,
'next': None
}
class lianbiao():
node = Node
def __init__(self):
self.head = None
self.p1 = self.p2 = None
self.__n = 0
self.i = 1
def create(self, num='00001', score=0, next=None):
self.__n += 1
a = self.node(num, score)
a.node['num'] = a.num
a.node['score'] = a.score
self.p1 = a.node
if self.__n == 1:
self.head = self.p1
else:
self.p2['next'] = self.p1
self.p2 = self.p1
def __iter__(self):
self.p1 = self.head
self.i = 1
return self
def __next__(self):
if self.i == 1:
self.i += 1
return self.p1
else:
self.p1 = self.p1['next']
if self.p1 != None:
self.i += 1
return self.p1
else:
raise StopIteration
@property
def length(self):
return self.__n
lian = lianbiao()
i = 1
while (i < 3):
i += 1
print("请输入数据: 学号5位数字组成, 成绩0-100分")
a = input()
b = input()
b = int(b)
lian.create(a, b)
for i in lian:
print(i)