一:链表的创建与输出(c++)
输入n个学生及其姓名与年龄
#include <iostream>
using namespace std;
typedef struct student
{
char name[10];
int age;
struct student *next;
}stu;
//创建链表
stu *createlist(int n)
{
stu *head = new stu;//定义头节点并分配空间
//创建一个新节点来记录上一个节点的next;
stu *pre = head;
for (int i = 0; i < n; i++)
{
stu* node = new stu;//创立一个新节点node分配空间
printf("输入第%d个学生的姓名和学号 : \n", i + 1);
cin >> node->name;
cin >> node->age;
pre->next = node;//将下个节点的next赋值为node的地址
node->next = NULL;
pre = node;//记录此节点方便下次的pre->next
}
return head;
}
//输出链表函数
void print(stu*head)
{
stu*node = head->next;//头节点的指针
while (node != NULL)
{
cout << node->name << " " << node->age << " " << endl;
node = node->next;//换到下一个节点
}
}
int main()
{
int n;
cin >> n;
stu *head1 = createlist(n);
print(head1);
}
自我认为啊,c++在链表创建这一块简单一点,毕竟开辟空间输入new,而c则要malloc,字符都少些。(不喜勿喷)
二:链表的排大小:
输入t个数 排序(从小到大)排
输入样例:
5
1 8 4 9 3
输出样例:
1->3->4->8->9
看了一后二就不写太多解释了
#include <iostream>
using namespace std;
typedef struct shuju
{
int s;
struct shuju *next;
}sj;
int main()
{
int a = 0,t;
cin >> t;
sj*head = new sj;
sj*pre = new sj;
pre = head;
sj*p; //必须用sj而不是int
sj*q; //必须用sj而不是int
while (t--)
{
sj*node = new sj;
cin >> node->s;
if (node->s == NULL) break;
pre->next = node;
node->next = NULL;
pre = node;
}
//冒泡排序
//核心
for (p = head->next; p != NULL; p = p->next)
{
for (q = p->next; q != NULL; q = q->next)
{
if (p->s > q->s)
{
t = p->s;
p->s = q->s;
q->s = t;
}
}
}
//核心
sj*node1 = head->next;
while (node1 != NULL)
{
if (a != 0) cout << "->";
cout << node1->s;
a++;
node1 = node1->next;
}
}
第三周总结
第三周写题不在状态,c++与c有些混淆,c++中函数记不太清