目录
一、LeetCode 24. 两两交换链表中的节点
题目链接:. - 力扣(LeetCode)
题目描述:给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
思路:
使用虚拟头结点,接下来就是交换相邻两个元素了,初始时,cur指向虚拟头结点,然后进行如下三步:
关键点在于:指针的位置,因为交换之后,原来的位置就不复存在了,我们一定要保存好,原来的位置信息。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
typedef struct ListNode ListNode;
//创建一个虚拟头结点,并将其指向head;
ListNode * shead =(ListNode *) malloc(sizeof(ListNode));
shead->next=head;
//构造一个指针
ListNode * cur=shead;
while(cur->next!=NULL && cur->next->next!=NULL)//判断结点的后两个位置都不为空,一个位置为空就是奇数个结点,不需要进行交换,两个位置都为空就是没有需要交换的结点。
{
ListNode* temp1=cur->next;//保留2位置
ListNode* temp2=temp1->next->next;//保留3位置
cur->next=cur->next->next;//head指向2
cur->next->next=temp1;//2指向1
temp1->next=temp2;//1指向3
cur= temp1;//cur滑向2,准备交换下一组
}
head=shead->next;
free(shead);
return head;
}
二、LeetCode 19.删除链表的倒数第N个节点
题目链接: