33,010
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
typedef struct node{
int d;
struct node *next;
}N;
N * construction(int d[], int n)//建立
{
N *h,*p,*pnew;
int i;
pnew = (N *)malloc(sizeof(N));
pnew->next = NULL;
h = pnew; p = pnew;
for(i = 0; i < n; i++)
{
pnew = (N *)malloc(sizeof(N));
pnew->d = d[i]; pnew->next = NULL;
p->next = pnew;
p = p->next;
}
return h;
}
void printList(N *h)//打印
{
N *p = h->next;
while(p != NULL)
{
printf("%d ",p->d);
p = p->next;
}
printf("\n");
}
void SWAP(N *h)//交换
{
N *pre2 = h;
N *pre = h->next;
N *p = pre->next;
while(p != NULL)
{ /*交换*/
pre2->next = p;
pre->next = p->next;
p->next = pre;
/*前移*/
pre2 = pre;
pre = pre->next;
if(pre == NULL) break;
p = pre->next;
}
}
int main(int argc, char *argv[])
{
N *head = (N *)malloc(sizeof(N));
int data[6] = {1,2,3,4,5,6};
head = construction(data,6);
printList(head);
SWAP(head);//交换
printList(head);
system("PAUSE");
return 0;
}