【高级操作系统】exp1:创建单链表,插入,遍历

丑陋的代码
编译:g++ -o main.c main

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

typedef struct stuInfo {
    
    
	char stuName[10];
	int Age;
} ElemType;

typedef struct node {
    
    
	ElemType data;
	struct node *next;
} ListNode, *ListPtr;

ListNode *CreateList() {
    
    
	ListNode *head =  (ListNode *)malloc(sizeof(ListNode));
	head->next = NULL;
	return head;
}

void PrintList(ListPtr ListHead) {
    
    
	ListPtr p = ListHead->next;
	printf("-----------输出链表内容,头插法------------\n");
	while (p != NULL) {
    
    
		printf("年龄 = %d\n", p->data.Age);
		p = p->next;
	}
	printf("----------------------------------------------\n");
}

void InsertList(ListPtr ListHead) {
    
    
	char name[10];
	int age;

	ListNode *node =  (ListNode *)malloc(sizeof(ListNode));

	printf("请输入姓名:\n");
	scanf("%s", name);
	printf("请输入年龄:\n");
	scanf("%d", &age);

//	(node->data).stuName = name;
	strcpy(node->data.stuName, name);
	node->data.Age = age;
//	printf("==%d\n", node->data.Age);

	ListPtr p = ListHead;
	while (p->next) {
    
    
		p = p->next;
	}
	p->next = node; // 尾插法

//	node->next = ListHead;
//	ListHead = node; // 头插法
}


int main(int argc, char **argv) {
    
    

	while (1) {
    
    
		printf("1 Create List\n");
		printf("2 Printf List\n");
		printf("3 Insert List\n");
		printf("4 Quit\n");
		char line[2];
		scanf("%s", line);
		char command = line[0];
//		getchar(); // 过滤掉回车
		ListNode *ListHead;
		switch (command) {
    
    
			case '1':
				ListHead = CreateList();
				break;
			case '2':
				PrintList(ListHead);
				break;
			case '3':
				InsertList(ListHead);
				break;
			case '4':
				return 0;
		}
	}
	cout << " 程序结束 " << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43154149/article/details/123674631