#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
typedef struct Node{
ElementType data;
struct Node *next;
}Node, *LinkList; /*LinkList为结构指针类型*/
LinkList createList();//创建链表
void insertHead(LinkList L, ElementType x);//头插法
void insertTail(LinkList L, ElementType x);//尾插法
void insertList(LinkList L, int i, ElementType x);//任意位置插法
void outputList(LinkList L);//输出链表
int deleteList(LinkList L, int n);//删除链表中的指定数字
void disposeList(LinkList L);//链表销毁
int deleteList(LinkList L, int i, ElementType *x);//删除链表中第i个结点,并且用x带出删除的值
int listLength(LinkList L); //获取链表长度
Node* locate(LinkList L, int i); //返回链表中第i个结点
Node* find(LinkList L, ElementType x);//链表中查找是否结点的数据等于x,如果存在,返回该结点的指针,否则返回NULL
int main()
{
LinkList L = createList();
int a[10] = {1,5,4,8,9,6,3,1,4,7};
for(int i=0; i<10; i++)
{
insertHead(L, a[i]);
}
outputList(L);
return 0;
}
LinkList createList()
{
LinkList L = (LinkList)malloc(sizeof(LinkList));
L->next = NULL;
return L;
}
void insertHead(LinkList L, ElementType x)
{
Node *p;
p = (LinkList)malloc(sizeof(Node));
p->data = x;
p->next = L->next;
L->next = p;
}
void insertTail(LinkList L, ElementType x)
{
Node *pre,*p,*s;
pre = L;
p = L->next;
while(p!=NULL){
pre = p;
p = p->next;
}
s = (Node *)malloc(sizeof(Node));
s->data = x;
s->next = pre->next;
pre->next = s;
}
void insertList(LinkList L, int i, ElementType x)
{
Node *pre, *p, *s;
int k = 1;
pre = L;
p = L->next;
while(p!=NULL && k<i)
{
pre = p;
p = p->next;
k++;
}
s = (Node *)malloc(sizeof(Node));
s->data = x;
s->next = pre->next;
pre->next = s;
}
void outputList(LinkList L){
Node *p;
p = L->next;
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int deleteList(LinkList L, int n)
{
LinkList pre,p;
pre = L;
p = L->next;
while(p != NULL && p->data != n){
pre = p;
p = p->next;
}
if(p == NULL){
return 0;
}else{
pre->next = p->next;
free(p);
return 1;
}
}
void disposeList(LinkList L)
{
Node *p;
while(p){
p = L->next;
free(L);
L = p;
}
}
int deleteList(LinkList L, int i, ElementType *x)
{
Node *p,*temp;
int k=0;
p = L;
while(p != NULL && k < i-1){
k++;
p = p->next;
}
if(p == NULL || i < 1 || p->next == NULL){
return 0;
}
temp = p->next;
p->next = temp->next;
*x = temp->data;
free(temp);
return 1;
}
int listLength(LinkList L)
{
LinkList p;
p = L->next;
int len=0;
while(p != NULL){
p = p->next;
len++;
}
return len;
}
Node* locate(LinkList L, int i)
{
Node *p;
p = L->next;
int k = 1;
while(p != NULL && k < i){
p = p->next;
k++;
}
return p;
}
Node* find(LinkList L, ElementType x)
{
Node *p;
p = L->next;
while(p != NULL && p->data != x){
p = p->next;
}
return p;
}