交换节点(线性表)
时间: 1ms 内存:128M
描述:
(线性表)编写一个算法来交换单链表中指针P所指结点与其后继结点,HEAD是该链表的头指针,P指向该链表中某一结点。
输入:
输入链表长度:6
输入链表:1 2 3 4 5 6
输入p指向的节点:5
输出:
1 2 3 4 6 5
示例输入:
5
7 6 9 8 2
3
示例输出:
7 6 8 9 2
提示:
参考答案(内存最优[752]):
#include"stdio.h"
#include"stdlib.h"
struct node
{
int data;
struct node *next;
}node;
struct node* create(int n)
{
struct node *head,*p1,*p2;
int i;
for(i=1;i<=n;i++)
{
p1=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p1->data);
if(i==1)
head=p1;
else
p2->next=p1;
p2=p1;
}
p1->next=0;
return head;
}
void fun(struct node *head,int n)
{
struct node *p,*q1=head,*q2=0;
int t=1;
while(t!=n)
{
t++;
q2=q1;
q1=q1->next;
}
if(n==1)
{
head=head->next;
q1->next=head->next;
head->next=q1;
}
else
{
p=q1->next;
q2->next=p;
q1->next=p->next;
p->next=q1;
}
printf("%d",head->data);
head=head->next;
while(head!=0)
{
printf(" %d",head->data);
head=head->next;
}
}
int main(){
int n;
struct node *head;
scanf("%d",&n);
head=create(n);
scanf("%d",&n);
fun(head,n);
return 0;
}
参考答案(时间最优[0]):
#include"stdio.h"
#include"stdlib.h"
struct node
{
int data;
struct node *next;
}node;
struct node* create(int n)
{
struct node *head,*p1,*p2;
int i;
for(i=1;i<=n;i++)
{
p1=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p1->data);
if(i==1)
head=p1;
else
p2->next=p1;
p2=p1;
}
p1->next=0;
return head;
}
void fun(struct node *head,int n)
{
struct node *p,*q1=head,*q2=0;
int t=1;
while(t!=n)
{
t++;
q2=q1;
q1=q1->next;
}
if(n==1)
{
head=head->next;
q1->next=head->next;
head->next=q1;
}
else
{
p=q1->next;
q2->next=p;
q1->next=p->next;
p->next=q1;
}
printf("%d",head->data);
head=head->next;
while(head!=0)
{
printf(" %d",head->data);
head=head->next;
}
}
int main(){
int n;
struct node *head;
scanf("%d",&n);
head=create(n);
scanf("%d",&n);
fun(head,n);
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。