双向链表的基本操作
2015-01-06 10:42
190 查看
双向链表的第个结点有两个指针,分别指向其直接前驱结点和直接后驱结点。这样就可以从表中任意的元素结点出发,从两个方向遍历链表。
结尾的r->next=NULL;一定不能少。不然出现内存泄露。
while()循环体两条语句不可以互换,可以修改为: printf("%d ",head->next->data); head=head->next;
while()循环体两条语句不可以互换,应先输出后,再向前移进。
第三句与第四句可以互换,但第一句与第二句互换就只能:p->front->next=s;s->front=p->front;
第三句与第四句可以互换,但第一句与第二句互换就只能:p->next->front=s;s->next=p->next;
第一句与第二句的位置可以互换。
1、双向链表结构体声明
typedef struct Node { int data; struct Node *front; struct Node *next; }Node;
2、尾插法构造带头结点双向链表
Node * createDLL_ByTail()//尾插法构造带头结点的双向链表 { Node *p,*r,*head; int x; head=(Node *)malloc(sizeof(Node)); head->front=NULL; r=head; while(scanf("%d",&x)!=EOF) { p=(Node *)malloc(sizeof(Node)); p->data=x; r->next=p; p->front=r; r=p; } r->next=NULL; return head; }
结尾的r->next=NULL;一定不能少。不然出现内存泄露。
3、头插法构造带头结点双向链表
Node * createDLL_ByHead()//头插法构造带头结点的双向链表 { Node *p,*r,*head; int x; head=(Node *)malloc(sizeof(Node)); r=NULL; head->front=NULL; while(scanf("%d",&x)!=EOF) { p=(Node *)malloc(sizeof(Node)); p->data=x; p->next=r; if(r==NULL) r=(Node *)malloc(sizeof(Node)); r->front=p; r=p; } p->front=head; head->next=r; return head; }返回之前的最后两句也不能少。不然出现指针指向未知。
4、双向链表的正向遍历
void positivePrintDLL(Node *head)//双向链表的正向遍历 { if(head->next==NULL) printf("This is a empty doubly link list\n"); while(head->next)//means head->next!=NULL { head=head->next; printf("%d ",head->data); } }
while()循环体两条语句不可以互换,可以修改为: printf("%d ",head->next->data); head=head->next;
5、双向链表的反向遍历
void reversePrintDLL(Node *tail)//双向链表的反向遍历 { if(tail->front==NULL) printf("This is a empty doubly link list\n"); while(tail->front)//means head->next!=NULL { printf("%d ",tail->data); tail=(*tail).front; } }
while()循环体两条语句不可以互换,应先输出后,再向前移进。
6、在结点p前插入结点s
s->front=p->front; p->front->next=s;//或者s->front->next=s; s->next=p; p->front=s;
第三句与第四句可以互换,但第一句与第二句互换就只能:p->front->next=s;s->front=p->front;
7、在结点p后插入结点s
s->next=p->next; p->next->front=s;//或者s->next->front=s; s->front=p; p->next=s;
第三句与第四句可以互换,但第一句与第二句互换就只能:p->next->front=s;s->next=p->next;
8、删除p结点
p->next->front=p->front; p->front->next=p->next; free(p);
第一句与第二句的位置可以互换。
相关文章推荐
- 双向链表的基本操作
- 链表的基本操作-双向链表
- 双向链表的基本操作
- c语言实现双向链表的基本操作
- 双向链表的基本操作
- 双向链表边的基本操作
- 数据结构 - C语言版 - 双向链表 所有基本操作
- 双向链表的基本操作实现
- 双向链表的基本操作
- 【C++/数据结构】双向链表的基本操作
- 不带头节点的双向循环链表的基本操作
- 双向循环链表的基本操作
- 双向链表基本操作
- 双向链表基本操作
- C语言实现双向链表的基本操作
- 算法(05):基本链表的操作及双向链表
- 实战数据结构(5)_双向循环链表的基本操作
- 实战数据结构(5)_双向循环链表的基本操作
- 数据结构学习之双向循环链表的基本操作(非递归实现)
- 双向循环链表的基本操作