题解 | #牛牛的链表交换#
牛牛的链表交换
http://www.nowcoder.com/practice/0e009fba6f3d47f0b5026b5f8b0cb1bc
#include <stdio.h>
#include <stdlib.h>
typedef struct link{
int data;
struct link *next;
}Link;
int main(void)
{
int len;
Link *head=(Link*)malloc(sizeof(Link));
Link *temp=head;
int arr[100]={0};
scanf("%d", &len);
for(int i=0;i<len;i++)
{
scanf("%d", &arr[i]);
}
for(int j=0;j<len;j++)
{
Link *a=(Link*)malloc(sizeof(Link));
a->data=arr[j];
a->next=NULL;
temp->next=a;
temp=temp->next;
}
temp=head;
Link *p=(Link*)malloc(sizeof(Link));
temp=temp->next;
p=temp->next;
temp->next=temp->next->next;
p->next=temp;
head->next=p;
temp=head;
Link *p1=(Link*)malloc(sizeof(Link));
Link *p2=(Link*)malloc(sizeof(Link));
for(int k=0;k<len-1;k++)
{
temp=temp->next;
if(k==len-3)
p2=temp;
}
p1=temp->next;
temp->next=NULL;
p1->next=temp;
p2->next=p1;
temp=head;
while(temp->next)
{
temp=temp->next;
printf("%d ", temp->data);
}
return 0;
}
#include <stdlib.h>
typedef struct link{
int data;
struct link *next;
}Link;
int main(void)
{
int len;
Link *head=(Link*)malloc(sizeof(Link));
Link *temp=head;
int arr[100]={0};
scanf("%d", &len);
for(int i=0;i<len;i++)
{
scanf("%d", &arr[i]);
}
for(int j=0;j<len;j++)
{
Link *a=(Link*)malloc(sizeof(Link));
a->data=arr[j];
a->next=NULL;
temp->next=a;
temp=temp->next;
}
temp=head;
Link *p=(Link*)malloc(sizeof(Link));
temp=temp->next;
p=temp->next;
temp->next=temp->next->next;
p->next=temp;
head->next=p;
temp=head;
Link *p1=(Link*)malloc(sizeof(Link));
Link *p2=(Link*)malloc(sizeof(Link));
for(int k=0;k<len-1;k++)
{
temp=temp->next;
if(k==len-3)
p2=temp;
}
p1=temp->next;
temp->next=NULL;
p1->next=temp;
p2->next=p1;
temp=head;
while(temp->next)
{
temp=temp->next;
printf("%d ", temp->data);
}
return 0;
}