链表 单链表 带头节点和不带头节点

#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 ]

*/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值