链表
c
typedef struct {
int val;
struct ListNode *next;
}ListNode;
初始化
c
ListNode* InitListNode(int val){
ListNode *a ;
a = (ListNode *)malloc(sizeof(ListNode));
a->next = NULL;
a->val = val;
return a;
}
插入
c
//在a后面插入b
void insert(ListNode *a , ListNode *b)
{
b->next = a->next;
a->next = b;
}
删除
c
//删除a后面的节点
void del( ListNode * a){
if(!a->next) return ;
ListNode * p = a->next;
ListNode * n = p->next;
a->next = n;
free(p);
}
访问节点
c
ListNode *access(ListNode *n,int index){
for (int i=0;i<index;i++){
if(n->next==NULL) return NULL;
n=n->next;
}
return n;
}
查找
c
int find(ListNode * node,int target){
int index = 0;
while(node){
if(node->val == target) return index;
node = node->next;
index++;
}
reutrn -1;
}
双向链表
c
typedef struct DoublyListNode{
int val;
struct DoublyListNode *prev;
struct DoublyListNode *next;
} DoublyListNode;
初始化
c
ListNode *newDoublyListNode(int val){
DoublyListNode *node;
node = (DoublyListNode *)malloc(sizeof(DoublyListNode));
node->prev = NULL;
node->next = NULL;
node->val = val;
}
析构函数
c
void delDoublyListNode(DoublyListNode *node){
free(node);
}
寻找第i个节点
c
DoublyListNode GetElem(DoublyListNode * node, int i){
for(int j=0;j<i;j++){
if(node->next == NULL){
printf("i too large!!\n");
return NULL;
}
node = node->next;
}
return node;
}
插入
c
//s插入到n的前面
void find(DoublyListNode *n ,DoublyListNode *s){
s->next = n->next->prev;
s->prev = n;
n->next->prev = s;
n->next = s;
}
删除
c
void delete(DoublyListNode *s){
s->prev->next = s->next;
s->next->prev = s->prev;
free(s);
}