两两交换链表中的结点
例:1->2->3->4->NULL
out:// 2->1->4->3->NULL
/*我的思想是:让指针p先指向head,然后确定head(头),因为第一次交换肯定是head和head->next,所以head肯定会移到head->next处充当新的头,接下来就是挂链,挪指针,同时注意新的尾的移动,总是p->next。
结束条件为:p==NULL;
#include<stdio.h>
#include<stdlib.h>
#define N 4
#include"lianbiao.h"//调用.h文件
ElemSN *Changenode(ElemSN *head)
{
ElemSN *p=head,*q=NULL,*tail;
while(p){
tail=p->next;
if(p==head){//头指针移动
head=tail;
}
else{
q->next=tail;
}//挂链
p->next=tail->next;
tail->next=p;
//跑链表
q=p;
p=p->next;
}
return head;
}
int main()
{
int a[N]={1,2,3,4};
ElemSN *head=NULL;
//创建链表
head=Createlink(a);
head=Changenode(head);
//输出链表
Printlink(head);
return 0;
}
其中**#include“lianbiao.h”文件如下**:
typedef struct node{
int data;
struct node *next;
}ElemSN;
ElemSN *Createlink(int a[])
{
ElemSN *h,*tail,*p;
//创建头结点
h=tail=(ElemSN *)malloc(sizeof(ElemSN));
h->data=a[0];
h->next=NULL;
for(int i=1;i<N;i++){
p=(ElemSN *)malloc(sizeof(ElemSN));
p->data=a[i];
p->next=NULL;
tail->next=p;
tail=p;
}
return h;
}
void Printlink(ElemSN *h)
{
ElemSN *p;
for(p=h;p!=NULL;p=p->next){
printf("%4d",p->data);
}
}