1. 程式人生 > >線性表——鏈表實現(單鏈表)

線性表——鏈表實現(單鏈表)

n) next lib AC 表結構 ini har == 是否

#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

using ElemType = int;

// 單鏈表結構 
class Node {
public:
	ElemType data;
	Node *next;
}; 


// 初始化單鏈表 
void initList(Node *head)
{
	char ch;
	int val;
	Node *q = head;
	while(1) {
		cout << "是否新增結點(y/n):";
		cin >> ch;
		if (ch == ‘n‘) {
			return;
		}
		cout << "請輸入結點的值:";
		cin >> val;
		Node *p = (Node*)malloc(sizeof(Node));
		p->data = val;
		p->next = nullptr;		// 尾插法 
		q->next = p;
		q = p;
	}
}

// add
void addNode(Node *head, int i, ElemType val)
{
	Node *q = head;
	int j = 0;
	bool flag = false;
	while (q->next != NULL)
	{
		if (j != i - 1) {
			j++;
			q = q->next;		// q指向第j個結點 
		}
		if (j == i - 1) {
			flag = true;
			Node *p = (Node*)malloc(sizeof(Node));
			p->data = val;
			p->next = q->next;
			q->next = p;
			break;
		}
	}
	if (!flag) {
		cout << "fail to add node\n";
		return;
	}
}

// del
void delNode(Node *head, int i)
{
	Node *q = head;
	int j = 0;
	bool flag = false;
	while(q->next != NULL) {
		if (j == i - 1) {
			flag = true;
			if (q->next->next == NULL) {
				q->next = NULL;
			}
			else {
				q->next = q->next->next;
			}
		}
		j++;
		q = q->next;
	}
	if (!flag) {
		cout << "fail to del node\n";
		return;
	}
}

void print(Node *head)
{
	Node *q = head;
	while (q->next != NULL) {
		q = q->next;
		cout << q->data << " ";
	}
	cout << endl;
}

int main()
{
	Node *head = (Node*)malloc(sizeof(Node));
	head->next = NULL;
	initList(head);
	print(head);
	int i;
	ElemType val;
	cin >> i >> val;
	addNode(head, i, val);
	delNode(head, 1);
	print(head);
}

  

線性表——鏈表實現(單鏈表)