{
int data;
struct node *next;
}node;
计算链表的结点数
int count(node *h){
node *p = h;
int i = 0;
if(p==NULL)
return 0;
else
{
for( ;p!=NULL;p=p->next)i++;
return i;
}
}
在链表中给定位置后插入所给的值
node* insert(node *h,int location,int info){
int c = 0;
node *p = h;
node *r = p;
node *q=(node *)malloc(sizeof(node *));
if(location<count(h))
{
for( ;p!=NULL;p=p->next)
{
c++;
if(c==location)
break;
}
q->next = p->next;
p->next = q;
q->data = info;
}
}
获得链表特定位置的值
int get_value(node *h,int location){
int c = 0;
node *p = h;
for( ;c<=location;c++)
p = p->next;
return p->data;
}
将一个链表插入另一个链表
node* insertOneinAnother(node* list_1,node* list_2,int start_1,int howmany)
{
int i=0;
int x=0;
for(i=1;i<=howmany;i++)
{
x = get_value(list_2,i);
list_1 = insert(list_1,start_1+i-1,x);
}
return list_1;
}
在单链表的末尾插入一个结点
node* push_back(node* last,int info)
{
//如果这是第一个结点
if(last==NULL){
last = (node *)malloc(sizeof(node));
last->data = info;
last->next = NULL;
return last;
}
//如果不是第一个结点
else{
node *p = (node *)malloc(sizeof(node));
if(p)
{
last->next = p;
p->data = info;
p->next = NULL;
}
//返回链表的末尾
return p;
}}
打印链表
void print(node *h){
int i;
node *p = h;
for(i=0;i<count(h);i++)
{
cout<<p->data<<"\t";
p=p->next;
}
}
获取链表尾结点的值
int back_element(node *h){
node *p;
for(p=h;p!=NULL;p=p->next)
return p->data;
}
交换单向链表的首尾结点
node* swap_head_tail(node *h){
node *p = h;
int temp = p->data;
p->data = back_element(h);
for( ;p->next!=NULL;p=p->next)
p->data = temp;
return p;
}
用给定值替换链表指定位置的值
node* replace(node *h,int location,int info)
{node *p = h;
for(int i=2;i<=location;i++)
p = p->next;
p->data = info;
return h;
}
交换除首尾结点之外的任何两个其他结点
node* swap(node *h,int loc_a,int loc_b){
int temp;
node *p = h;
temp = get_value(h,loc_a);
p = replace(p,loc_a,get_value(h,loc_b));
p = replace(p,loc_b,temp);
return p;
}
删除由下标数字给定的特定结点
node* delete_at(node *h,int location)
{
int c = 0;
node *p = h;
node *r = p;
node *x;
if(location<count(h))
{
for( ;p!=NULL;p=p->next)
{
c++
if(c==location-1);
break;
}
//将p指针定位到要删除的结点前面 location从0开始
x = p->next;
p->next = p->next->next;
free(x);
}
return r;
}
删除一个范围的元素
node* delete_range(node *h,int start,int finish)
{
node *p = h;
int c = 0;
int k = 0;
for(c=start,k=0;c<finish;c++,k++)
delete_at(h,c-k);
return p;
}
让链表数据项唯一(删除重复项,保留第一次出现的)
node* distinct(node *list)
{
node *a = NULL;
int i = 0;
int j = 0;
for(i=1;i<count(list);i++)
{
for(j=1;j<count(list);j++)
{
//i=j时,元素不是副本,就是原始的元素
if(i!=j&&get_value(list,i)==get_value(list,j))
//j位置元素是副本,删除
list = delete(list,j);
}
}
return list;
}
删除链表的最后一个元素
node* pop_back(node *h)
{
node *p = h;
node *r = p;
for( ; ;)
{
if(p->next->next==NULL)
{
free(p->next->next);
p->next = NULL;
break;
}
p = p->next;
}
return r;
}