双链表学习
有了单链表的理解,双链表就好些了。双链表的遍历,查找某个结点和单链表比较相似。只是在删除和插入的时候要指明前后的指针
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node *pre;
struct node *next;
}Node;
Node *create(int n)
{
Node *head;
head = (Node*)malloc(sizeof(Node));
if(head==NULL)
return;
head->pre = NULL;
head->next = NULL;
Node *p = head;
int i;
for(i=0;i<n;i++)
{
Node *cur;
cur = (Node*)malloc(sizeof(Node));
if(cur==NULL)
return;
cur->data = i+1;
p->next = cur;
cur->pre = p;
p = cur;
}
p->next = NULL;
return head;
}
void print(Node *L)
{
Node *cur = L->next;
while(cur!=NULL)
{
printf("%d,",cur->data);
cur = cur->next;
}
printf("\n");
}
Node *insert(Node *L,int k,int data)
{
int i=1;
Node *cur = L->next;
while(i<k&&!cur)
{
cur = cur->next;
printf("%d\n",cur->data);
++i;
}
if(cur==NULL||i>k)
return;
Node *insert_node;
insert_node = (Node*)malloc(sizeof(Node));
if(insert_node==NULL)
return;
//必须指明前后的指针
insert_node->data = data;
insert_node->pre = cur;
insert_node->next = cur->next;
cur->next->pre = insert_node;
cur->next = insert_node;
return L;
}
Node *delete(Node *L,int k)
{
Node *cur = L->next;
if(!cur)
return;
int i=1;
while(i<k&&cur!=NULL)
{
cur = cur->next;
++i;
}
if(i>k||!cur)
return;
//其实删除比较好理解。
cur->pre->next = cur->next;
cur->next->pre = cur->pre;
free(cur);
return L;
}
int main(void)
{
int n = 10;
Node *L = create(n);
print(L);
Node *iL = insert(L,2,100);
print(iL);
Node *dL = delete(L,14);
print(dL);
return 0;
}
--------EOF---------
微信分享/微信扫码阅读
微信分享/微信扫码阅读