1. 程式人生 > >C/C++從鍵盤讀入連續輸入的資料(以回車結束),並將資料存入連結串列。

C/C++從鍵盤讀入連續輸入的資料(以回車結束),並將資料存入連結串列。

  要求新建一個連結串列,連結串列從鍵盤讀取一組連續輸入的資料,每個資料之間以一個空格分隔,當遇到換行符時,停止讀取。
  下面是自己總結的比較簡單的實現方法。
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;
}