



/*
*有头结点版本
*作者:善良超哥哥
*时间:2014-8-16
*/
//LinkList.h
#ifndef _LIMKLIST_H_
#define _LINKLIST_H_
typedef struct LNode{
char data;
struct LNode *next;
}LNode;
typedef struct{
LNode *head; //指向第一个结点的指针
int len; //链表长度
}LinkList;
//创建链表,尾插法
void CreateList(LinkList *L);
//在第i个位置插入元素e
int ListInsert(LinkList *L,int i,char e);
//删除第i个位置的元素,并用*e返回
int ListDelete(LinkList *L,int i,char *e);
//遍历打印链表中的所有元素
void ListPrint(LinkList *L);
#endif//LinkList.c
/*
有头结点的链表实现
*/
#include "LinkList.h"
#include <stdio.h>
#include <stdlib.h>
//创建链表,尾插法
void CreateList(LinkList *L)
{
L->head = malloc(sizeof(LNode));//创建头结点
L->head->next = NULL;
L->len = 0;
//开始输入字符,创建链表,以#结束
char c;
LNode *p = L->head;
while((c = getchar()) != '#')
{
LNode *s = malloc(sizeof(LNode));
s->data = c;
p->next = s;
p = s;
++(L->len);
}
p->next = NULL;
}
//在第i个位置插入元素e
int ListInsert(LinkList *L,int i,char e)
{
if(i < 1 || i > L->len || L == NULL)
{
return 0;//失败
}
LNode *p = L->head;
for(int j = 1; j < i; j++)
{
p = p->next;
}
LNode *s = malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
++(L->len);
return 1;
}
//删除第i个位置的元素,并用*返回
int ListDelete(LinkList *L,int i,char *e)
{
if(L == NULL || i < 1 || i >= L->len)
{
return 0;//失败了
}
LNode *p = L->head;
for(int j = 1; j < i; j++)
{
p = p->next;
}
//删除p指针指向的结点的下一个结点
LNode *q = p->next;
p->next = q->next;
free(q);
--(L->len);
return 1;
}
//遍历打印链表中的所有元素
void ListPrint(LinkList *L)
{
LNode *p = L->head->next;
while(p!=NULL)
{
printf("%c",p->data);
p = p->next;
}
printf("\n");
}
/*
*无头结点版本
*作者:善良超哥哥
*时间:2014-8-16
*/
//LinkList.h
#ifndef _LIMKLIST_H_
#define _LINKLIST_H_
typedef struct LNode{
char data;
struct LNode *next;
}LNode;
typedef struct{
LNode *head; //指向第一个结点的指针
int len; //链表长度
}LinkList;
//创建链表,尾插法
void CreateList(LinkList *L);
//在第i个位置插入元素e
int ListInsert(LinkList *L,int i,char e);
//删除第i个位置的元素,并用*e返回
int ListDelete(LinkList *L,int i,char *e);
//遍历打印链表中的所有元素
void ListPrint(LinkList *L);
#endif

重刷数据结构,小题大做,——难道非要头结点吗?,布布扣,bubuko.com
原文地址:http://blog.csdn.net/candcplusplus/article/details/38617733