C/C++从键盘读入连续输入的数据(以回车结束),并将数据存入链表。

版权声明:欢迎转载,但请注明出处https://me.csdn.net/qq_28753373 。谢谢! https://blog.csdn.net/qq_28753373/article/details/84113107

  要求新建一个链表,链表从键盘读取一组连续输入的数据,每个数据之间以一个空格分隔,当遇到换行符时,停止读取。
  下面是自己总结的比较简单的实现方法。
C:

#include <stdio.h>

typedef struct ListNode *node;
struct ListNode {
	int key;
	node next;
};

node CreateList();
void ListInsert(node l, int element);
void PrintList(node l);
void DeleteList(node l);

int main() {
	node l = CreateList();

	int element;
	printf("Please input the element of the list nodes:\n");
	/*从键盘读入数据*/
	do {
		scanf("%d", &element);
		ListInsert(l, element);
	} while (getchar() != '\n');	//吸收每一个数据后的字符并判断

	PrintList(l);
	DeleteList(l);

	return 0;
}

node CreateList() {
	node l = (node)malloc(sizeof(struct ListNode));
	l->next = NULL;
	return l;
}

void ListInsert(node l, int element) {
	node tmp = l;
	while (tmp->next)
		tmp = tmp->next;

	node NewNode = (node)malloc(sizeof(struct ListNode));
	NewNode->key = element;
	NewNode->next = NULL;
	tmp->next = NewNode;
}

void PrintList(node l) {
	node tmp = l->next;
	while (tmp) {
		printf("%-3d", tmp->key);
		tmp = tmp->next;
	}
	printf("\n");
}

void DeleteList(node l) {
	while (l) {
		node tmp = l->next;
		free(l);
		l = tmp;
	}
}

C++:

#include <iostream>

using namespace std;

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) :val(x), next(NULL) {}
};

ListNode *CreateList();
void AddNode(ListNode *head, int element);
void PrintList(ListNode *head);

int main() {
	int element;
	ListNode *result;

	ListNode *l = CreateList();
	cout << "Please input the data of linklist:" << endl;

	/*从键盘读入数据读入数据*/
	while (cin >> element) {
		AddNode(l, element);
		if (cin.get() == '\n') break;	//吸收每一个数据后的字符并判断
	}
	PrintList(l);
}

/*创建空链表*/
ListNode *CreateList() {
	ListNode *head = new ListNode(-1);
	return head;
}

/*向表中添加结点*/
void AddNode(ListNode *head, int element) {
	if (!head) {
		cout << "The Linklist is NULL!";
		exit(EXIT_FAILURE);
	}

	ListNode *tmp = head;
	while (tmp->next) {
		tmp = tmp->next;
	}
	ListNode *NewNode = new ListNode(element);
	tmp->next = NewNode;
}

/*打印链表*/
void PrintList(ListNode *head) {
	if (!head) {
		cout << "The Linklist is NULL!" << endl;
		exit(EXIT_FAILURE);
	}

	ListNode *p = head->next;
	while (p) {
		cout << p->val << " ";
		p = p->next;
	}
	cout << endl;
}

猜你喜欢

转载自blog.csdn.net/qq_28753373/article/details/84113107