仿linux list 的双链表

主要熟悉一下如何使用双链表,尤其看节点定义在其他结构体中如何使用; 此处, 链表节点和其他节点公用首地址;
其他节点的含义是业务实现中有具体含义的节点。 如果链表节点并未定义在业务节点的起始处, linux 有container_of(ptr,type,member)
用于完成由链表节点到业务节点的推算;

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

struct nodelink{
	struct nodelink* pre;
	struct nodelink* next;
};

struct node {
	struct nodelink link;
	int val;
};

struct node head;

void init() {
	(head.link).pre = NULL;
	(head.link).next = NULL;
	head.val = 0;
}

void insert(struct node* ins){	
	struct nodelink* tmp = head.link.next;
	head.link.next = &(ins->link);
	ins->link.pre = &(head.link);
	ins->link.next = tmp;
	if(tmp != NULL) {	
		tmp->pre = &(ins->link);		
	}
		
	head.val++;
}

void readlink() {
	struct node* nptr = &head;
	struct nodelink  *curlink = &(nptr->link);
	int cnt = 0;
	while(curlink != NULL ){
		cout << nptr->val << "  ";
		nptr =(struct node*) curlink->next;
		curlink = curlink->next;			
	}
}


int main(){
	init();
	
	struct node ins;
	ins.val = 10;
	insert(&ins);
	
	struct node ins1;
	ins1.val = 11;
	insert(&ins1);
	
	struct node ins2;
	ins2.val = 12;
	insert(&ins2);
		
	readlink();

	return 0;
}

猜你喜欢

转载自www.cnblogs.com/simk/p/13164219.html