#include "stdlib.h"
#include "malloc.h"
typedef char elemType;
typedef struct SNode
{
elemType data;
struct SNode *next;
}*LNode,Node;
/*带头结点的单链表,初始时一定返回的是指向头结点的地址,
所以一定要用二重指针,否则将导致内存访问失败或异常,
其实不带头结点的也一样要用二重指针,这是因为他会涉及到头指针的更改
(相对与main函数Init为外部函数,函数外部更改),
不带头结点的初始化如下注释部分:
void Init(Node **h)//不带头结点
{
*h = NULL;
}
*/
void Init(Node **h)//带头节点
{
*h = (Node*)malloc(sizeof(Node));
if(!*h)
{
printf("error!");
return;
}
(*h)->data = '/0';
(*h)->next = NULL;
printf("this initialize link head physics address is : %d/n",*h);
printf("this initialize link head data is : %d/n",(*h)->data);
printf("this initialize link head next address is : %d/n",(*h)->next);
printf("this initialize link head pointer is : %d/n",h);
}
/*
带头结点的插入操作只用指针就可以了,但如果是不带头结点的则必须用二重指针:
代码如下:
void insertfirst(Node **h,elemType x)//不带头结点
{
Node* newp = (Node*)malloc(sizeof(Node));
newp->data = x;
newp->next = *h;
*h = newp;
}
*/
void insertfirst(Node *h,int i,elemType x)//带头节点的插入
{
Node* p = h;
Node* newp = (Node*)malloc(sizeof(Node));
if(i!=0)
{}
newp->data = x;
newp->next = h->next;
h->next = newp;
}
void insertpos(Node *h,int i,elemType x)//带头节点的插入
{
int t = 0;
Node* p = h;
Node* newp = (Node*)malloc(sizeof(Node));
printf("this h is : %d /n",h);
printf("this *h is : %d /n",*h);
printf("this h->data is : %d /n",h->data);
printf("this h->next is : %c /n",(char)h->next->data);
while(p -> next != NULL)
{
if(t == i)
break;
p=p->next;
t++;
}
if(t>i)
{
printf("error!/n");
return;
}
newp->data = x;
newp->next = p->next;
p->next = newp;
}
/*
void travel(Node *h)//不带头节点的遍历
{
while(h)
{
printf("/nthe data is : [ %c ]",h->data);
h=h->next;
}
}
*/
void travel(Node *h)//带头节点的遍历
{
Node *p;
p= h->next;
while(p)
{
printf("the data is : [ %c ]/n",p->data);
p=p->next;
}
}
/*
void main()//不带头节点的主函数
{
int i = 0;
char a[]={'a','b','c','d','e'};
LNode h;
Init(&h);
for(i=0;i<5;i++)
{
insertfirst(&h,a[i]);
}
travel(h);
}
*/
void main()
{
int i = 0;
char a[]={'a','b','c','d','e'};
LNode h;
Init(&h);
for(i=4;i>-1;i--)
{
insertfirst(h,0,a[i]);
}
insertpos(h,2,'x');
travel(h);
}
/**
输出:
this initialize link head physics address is : 3681864
this initialize link head data is : 0
this initialize link head next address is : 0
this initialize link head pointer is : 1245036
this h is : 3681864
this *h is : 3670528
this h->data is : 0
this h->next is : a
the data is : [ a ]
the data is : [ b ]
the data is : [ x ]
the data is : [ c ]
the data is : [ d ]
the data is : [ e ]
*/