对双链表做个总结,下面是一系列基本操作
#include <stdlib.h>
#define null 0
#define MAXSIZE 50
struct strlnode
{
int data;
struct strlnode *plast;
struct strlnode *pnext;
};
一、创建双链表
void create(struct strlnode **p, int x) /*创建双链表(表头节点)*/
{
struct strlnode *q;
q = (struct strlnode *)malloc(sizeof(struct strlnode));
q->data = x;
q->plast = null;
q->pnext = null;
*p = q;
return;
}
二、在链表第i个位置插入数据等于x的节点
void insertnode(struct strlnode **p, int i, int x) /* 在链表第i个位置插入数据等于x的节点 */
{
struct strlnode *ptr,*q;
ptr= (struct strlnode *)malloc(sizeof(struct strlnode));
ptr->data=x;
q=*p; //head
//插入时指针的调整都是先后再前
if(i==0) //表头
{
ptr->pnext=q;
ptr->plast=null;
q->plast=ptr;
*p=ptr;
return;
}
for(int k=1;k<i;k++) //依次向后移
{
q=q->pnext;
if(q==null)
return;
}
if(q->pnext==null) //表尾
{
ptr->pnext=null;
ptr->plast=q;
q->pnext=ptr;
return;
}
q->pnext->plast=ptr; //除了表头表尾的一般情况
ptr->pnext=q->pnext;
q->pnext=ptr;
ptr->plast=q;
}
三、删除链表中第i个节点
void deletenode(struct strlnode **p, int i) /* 删除链表中第i个节点 */
{
struct strlnode *q,*ptr;
q=*p;
for(int k=1;k<i;k++)
{
q=q->pnext;
if(q==null)
return;
}
if(q->pnext==null)
return;
ptr=q->pnext;
ptr->pnext->plast=q;
q->pnext=ptr->pnext;
delete ptr;
ptr=null;
}
四、获取链表中节点个数
int getnodenum(struct strlnode **p) /*获取链表中节点个数*/
{
int nodenum = 0;
struct strlnode *q=*p;
while(q!=null)
{
nodenum++;
q=q->pnext;
}
return nodenum;
}
五、使用链表实现大整数相加
void bignumberplus(struct strlnode **plus, struct strlnode **p, struct strlnode **q) /* 使用链表实现大整数相加 */
{
struct strlnode *ptr=*plus;
struct strlnode *pt=*p;
struct strlnode *qt=*q;
int c,r;
if(*p==null&&*q==null)
return;
if(*p==null)
{
int i=0;
while(qt!=null)
{
insertnode(plus,i++,qt->data);
qt=qt->pnext;
}
return;
}
if(*q==null)
{
int i=0;
while(pt!=null)
{
insertnode(plus,i++,pt->data);
pt=pt->pnext;
}
return;
}
while(pt->pnext!=null)
pt=pt->pnext;
while(qt->pnext!=null)
qt=qt->pnext;
r=pt->data+qt->data;
c=r>9?1:0;
r=(c==0)?r:r-10;
ptr->data=r;
pt=pt->plast;
qt=qt->plast;
while(pt!=null&&qt!=null)
{
r=pt->data+qt->data+c;
c=r>9?1:0;
r=(c==0)?r:r-10;
insertnode(plus,0,r);
pt=pt->plast;
qt=qt->plast;
}
if(pt!=null)
{
while(pt!=null)
{
r=pt->data+c;
c=r>9?1:0;
r=(c==0)?r:r-10;
insertnode(plus,0,r);
pt=pt->plast;
}
}
else if(qt!=null)
{
while(qt!=null)
{
r=qt->data+c;
c=r>9?1:0;
r=(c==0)?r:r-10;
insertnode(plus,0,r);
qt=qt->plast;
}
}
if(c==1)
insertnode(plus,0,1);
}
六、将数组写入链表中,链表中的数据的先后顺序和数组中的顺序要保持一致
void readtolnode(struct strlnode **p, int *a, int size) /* 将数组写入链表中,链表中的数据的先后顺序和数组中的顺序要保持一致 */
{
int j = 0;
int data = 0;
struct strlnode *s = *p;
s->data = *(a + (size-1));
for(j = 2; j < (size+1); j++)
{
data = *(a + (size-j));
insertnode(p, 0, data);
}
return;
}
七、 将链表写入数组中,数组中的数据的先后顺序和链表中的顺序要保持一致
void writetosqlist(int *a, struct strlnode *p) /* 将链表写入数组中,数组中的数据的先后顺序和链表中的顺序要保持一致 */
{
int j = 0;
struct strlnode *s = p;
while(s != null)
{
*(a + j) = s->data;
s = s->pnext;
j++;
}
return;
}