数据结构<链表>踩坑记录

链表

双重指针的理解加深

#include <iostream>
using namespace std;

typedef int ElemType;
// define node Structure
typedef struct node{
	ElemType data;
	struct node* next;
} Node;

// function statement
bool initLink(Node**);
bool addElemNode(Node*, ElemType);
int getLength(Node*);
void traverseList(Node*);


int main(){
	Node* headPoint = NULL;
	initLink(&headPoint);
	if (headPoint == NULL) cout << "is null" << endl;
	cout << headPoint->data << endl;
	addElemNode(headPoint, 1);
	addElemNode(headPoint, 1);
	addElemNode(headPoint, 1);
	addElemNode(headPoint, 1);
	traverseList(headPoint);
	return 0;
}

// init LinkList sign***
bool initLink(Node** node){
	*node = new Node;
	if (node == NULL) {cout << "init fail!" << endl; exit(-1);}
	(*node)->data = -1;
	(*node)->next = NULL;
	return true;
}

//add Element node
bool addElemNode(Node* node, ElemType value){
	Node* lastNode = node;
	while (lastNode->next != NULL) lastNode = lastNode->next;
	Node* newNode = new Node;
	if (newNode == NULL) {cout << "add fail" << endl; exit(-1);}
	newNode->data = value;
	newNode->next = NULL;
	lastNode->next = newNode;
	return true;
}

// get link length
int getLength(Node* node){
	Node* pNode = node->next;	
	int length = 0;
	while (pNode != NULL){
		length++;
		pNode = pNode->next;
	}
	return length;
}

void traverseList(Node* node) {
	Node* pNode = node->next;
	while (pNode != NULL){
		cout << "data:" << pNode->data << endl;
		pNode = pNode->next;
	}
}

注: 要修改的是 头指针的内容 所以是双重指针

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值