myList.h
//计算member在type中的位置
#if defined(offsetof)
#undef offsetof
#define offsetof(type, member) (size_t)(&((type*)0)->member)
//根据member的地址获取type的起始地址
#define container_of(ptr, type, member) \
(type *)((char *)ptr - offsetof(type, member));
#endif
struct list_head{
struct list_head *next, *prev;
};
static inline void INIT_LIST_HEAD(struct list_head *list)
{
list->next = list;
list->prev = list;
}
//插入节点
static inline void __list_add(struct list_head *new_,
struct list_head *prev,
struct list_head *next)
{
next->prev = new_;
new_->next = next;
new_->prev = prev;
prev->next = new_;
}
static inline void list_add(struct list_head *new_, struct list_head *head)
{
__list_add(new_, head, head->next);
}
static inline void list_add_tail(struct list_head *new_, struct list_head *head)
{
__list_add(new_, head->prev, head);
}
//删除节点
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
next->prev = prev;
prev->next = next;
}
static inline void list_del(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
entry->next = NULL;
entry->prev = NULL;
}
tset程序
#include <iostream>
#include <string>
#include "myList.h"
using namespace std;
struct NodeDong{
int i;
char ch;
list_head dongList;
NodeDong(int i = 0, char ch = 0) :i(i), ch(ch){}
};
list_head *CreateListByString(string str){
if (str.empty())
return NULL;
int len = str.length();
list_head *head = new list_head;
INIT_LIST_HEAD(head);
int idx = 0;
while (idx < len){
NodeDong *node = new NodeDong(idx, str[idx]);
list_add_tail(&node->dongList, head);
++idx;
}
return head;
}
void print(list_head *head, int len){
int i = 0;
head = head->next;
while (i < len){
NodeDong *node = container_of(head, NodeDong, dongList);
cout << node->i << " -> " << node->ch << endl;
head = head->next;
++i;
}
}
int main()
{
string str = "hello dong";
list_head *head = CreateListByString(str);
print(head, str.length());
system("pause");
return 0;
}
/*
0 -> h
1 -> e
2 -> l
3 -> l
4 -> o
5 ->
6 -> d
7 -> o
8 -> n
9 -> g
*/