题目
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4] 输出:[2,1,4,3]
示例 2:
输入:head = [] 输出:[]
示例 3:
输入:head = [1] 输出:[1]
提示:
- 链表中节点的数目在范围
[0, 100]
内 0 <= Node.val <= 100
思路
难点是交换时注意节点之间的关系,前后的连接。
代码
#include<stdio.h>
#include<stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
}Node;
void Creat(struct ListNode** head);
struct ListNode* swapPairs(struct ListNode* head);
int main()
{
Node*head;
Creat(&head);
Node*res=swapPairs(head);
res=res->next;
while(res!=NULL)
{
printf("%d ",res->val);
res=res->next;
}
return 0;
}
void Creat(struct ListNode** head)
{
*head=(Node*)malloc(sizeof(Node));
int n;
(*head)->next=NULL;
scanf("%d",&n);
Node*end,*ins;
end=*head;
for(int i=0;i<n;i++)
{
ins=(Node*)malloc(sizeof(Node));
int a;
scanf("%d",&a);
ins->val=a;
ins->next=NULL;
end->next=ins;
end=ins;
}
}
struct ListNode* swapPairs(struct ListNode* head)
{
struct ListNode*temp1=(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode*temp2=(struct ListNode*)malloc(sizeof(struct ListNode));
int len=0;
temp1=head->next;
while(temp1!=NULL)
{
temp1=temp1->next;
len++;
}
if(len==0||len==1)
return head;
else
{
temp1=head->next;
temp2=temp1->next;
}
struct ListNode*last=head;
while(temp1!=NULL&&temp2!=NULL)
{
struct ListNode*temp=temp2->next;
temp1->next=temp;
temp2->next=temp1;
last->next=temp2;
last=temp1;
if(temp!=NULL)
{
temp1=temp;
temp2=temp->next;
}
else break;
}
return head;
}
总结
以上就是今天要讲的内容。