《数据结构与算法实战》3-2:链表

链表是学数据结构的童鞋最先接触的一种数据结构。C语言的链表需要自己用指针和结构体去构造,也最能训练队链表的理解程度。C++可以使用STL中的list实现,而Python则可以直接使用列表类型,列表类型可以当做数组、顺序表、链表。

下面是C的实现方式

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;

struct Node{
	int data;
	struct Node* next;
};

void init(struct Node** phead) {
	*phead = NULL;
}

int getLength(struct Node* head) {
	int length = 0;
	while (head) {
		length++;
		head = head->next;
	}
	return length;
}

void print_list(struct Node* head) {
	while (head) {
		printf("%d,", head->data);
		head = head->next;
	}
	cout << endl;
}

struct Node* create_node(int x)
{
	struct Node* t;
	t = (struct Node*)malloc(sizeof(struct Node));
	t->data = x;
	t->next = NULL;
	return t;
};

struct Node* find_Kth(struct Node* head, int k) {
	int cnt = 1;
	struct Node* p;
	p = head;
	while (p && cnt<k)
	{
		p = p->next;
		cnt++;
	}
	return p;
}

int insert(struct Node** phead, int k, int x) {
	if (k < 1) {
		return 0;
	}
	else if (k == 1) {
		struct Node* t;
		t = create_node(x);
		t->next = *phead;
		*phead = t;
		return 1;
	}
	else {
			struct Node* p;
			p = find_Kth(*phead, k-1);
			if (p) {
				struct Node* t;
				t = create_node(x);
				t->next = p->next;
				p->next = t;
				return 1;
			}
			else {
				return 0;
			}
	}
}

int remove_node(struct Node** phead, int k, int *px) {
	if (k < 1)	return 0;
	else if (k == 1) {
		if (*phead) {
			*px = (*phead)->data;
			*phead = (*phead)->next;
			return 1;
		}
		else return 0;
	}
	else {
		struct Node* p;
		p = find_Kth(*phead, k - 1);
		if (p == NULL || p->next == NULL)	return 0;
		struct Node* t;
		t = p->next;
		p->next = t->next;
		*px = t->data;
		free(t);
		return 1;
	}
}

int main() {
	struct Node* head;

	//初始化
//	head = NULL;
	init(&head);

	//求表长
	cout<<getLength(head)<<endl;

	//插入链表
	int flag = 0;
	flag=insert(&head, 1,11);
	//cout << flag << endl;
	insert(&head, 1,22);
	insert(&head, 2, 33);
	insert(&head, 4, 44);
	insert(&head, 6, 55);

	//打印链表
	print_list(head);
	//删除节点
	int x=0;
	remove_node(&head,5,&x);
	cout << x << endl;
	print_list(head);
	system("pause");
	return 0;
}

C++的使用方式

#include <iostream>
#include <list>
using namespace std;

int main(){
	list<int> a;	//a是一个链表 
	a.push_back(11);
	a.push_back(22);
	a.push_back(33); 
	a.insert(a.begin(),666);	//a.begin()+1 会报错的。因为 C++默认链表地址是不连续的,而采用+1操作是需要在顺序存储结构中才能实现 
	list<int>::iterator it;
	for(it=a.begin() ;it!=a.end() ;it++)
		cout<<&(*it)<<","<<*it<<" "; 
	a.erase()
	for(int i:a){
		cout<<i<<" ";
	}
	cout<<endl;
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吉大秦少游

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值