#include "list.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//创建头结点
Node* create_phead()
{
Node *phead=(Node*)malloc(sizeof(Node));
phead->next=NULL;
return phead;
}
//在末尾添加一个元素
void add_node(Node* phead,int d)
{
Node* p=(Node*)malloc(sizeof(Node));
p->data=d;
p->next=NULL;
Node*q=phead;
while(q->next!=NULL)
{
q=q->next;
}
q->next=p;
}
//getData –查找第n个元素的值
int getData(Node *phead,int n)
{
int i=0;
if(n<1) return 0;
Node *p=phead;
while(p->next!=NULL&&i<n)
{
++i;
p=p->next;
// printf("%d-%d\n",i,p->data);
}
return p->data;
}
//getByIndex –查找第n个结点
Node* getByIndex(Node *phead,int n)
{
int i=0;
if(n<1) return phead;
Node *p=phead;
while(p->next!=NULL&&i<n)
{
++i;
p=p->next;
}
return p;
}
//getPosition –查找元素d的位置,如果成功返回d的位置,不成功返回-1
int getPos(Node *phead,int d)
{
Node *p=phead;
int i=0;
while(p->next!=NULL)
{
++i;
p=p->next;
if(d==p->data)
return i;
}
return -1;
}
//输出链表元素
void print(Node* phead)
{
Node* q=phead;
while(q->next!=NULL)
{
q=q->next;
printf("%d\n",q->data);
}
}
//移除第n个结点
void del_node(Node *phead,int n)
{
/* Node *prev;
Node *q=phead;
int i=0;
while(q->next!=NULL&&i<n)
{
++i;
prev=q;
q=q->next;
}
prev->next=q->next;
free(q);
q=NULL;
*/
Node* prev=getByIndex(phead,n-1);
Node* find=getByIndex(phead,n);
prev->next=find->next;
free(find);
find=NULL;
}
//链表清空
void clear(Node *phead)
{
Node *q=NULL;
while(phead!=NULL)
{
q=phead->next;
phead->next=NULL;
free(phead);
phead=q;
}
}