1、LeetCode24
struct ListNode* swapPairs(struct ListNode* head){
// 虚拟头结点
struct ListNode* dummyHead = (struct ListNode*) malloc(sizeof(struct ListNode));
dummyHead->next = head;
struct ListNode* cur = dummyHead;
while (cur->next != NULL && cur->next->next != NULL) {
struct ListNode *p = cur->next;
cur->next = p->next;
p->next = p->next->next;
cur->next->next = p;
cur = p;
}
head = dummyHead->next;
return head;
}
2、LeetCode19
使用双指针,一次遍历。
快指针先移动n+1次,之后快慢指针同时移动,直至快指针为NULL,此时,慢指针指向倒数n+1个位置。
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
// 虚拟头结点
struct ListNode *dummyHead = (struct ListNode*) malloc(sizeof(struct ListNode));
dummyHead->next = head;
// 快慢指针
struct ListNode *fast = dummyHead, *slow = dummyHead;
// count计数,计fast指针移动的次数是否达到n+1,达到则slow指针开始移动
int count = 0;
while (fast != NULL) {
fast = fast->next;
if (count < n + 1) {
count++;
} else {
slow = slow->next;
}
}
// 防止n超出链表长度情况
if (count < n + 1) return head;
struct ListNode *p = slow->next;
slow->next = p->next;
head = dummyHead->next;
free(p);
free(dummyHead);
return head;
}
3、LeetCode160
只有当链表 headA和 headB都不为空时,两个链表才可能相交。因此首先判断链表 headA 和
headB是否为空,如果其中至少有一个链表为空,则两个链表一定不相交,返回null。当链表headA 和headB 都不为空时,创建两个指针pAtoB和pBtoA,初始时分别指向两个链表的头节点
headA和headB,然后将两个指针依次遍历两个链表的每个节点。
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
// 建立双指针,起始时分别指向链表A(n)和链表B(m)
// 当遍历次数分别达到n和m时,改变指向,分别指向B和A
struct ListNode *pAtoB = headA, *pBtoA = headB;
// 只要有一个链表为空,则返回NULL
if (!pAtoB || !pBtoA) return NULL;
// 当两个指针都为NULL时,表示已经遍历了n+m次
while (pAtoB || pBtoA) {
if (pAtoB == NULL && pBtoA != NULL) {
pAtoB = headB;
} else if (pBtoA == NULL && pAtoB != NULL) {
pBtoA = headA;
}
if (pAtoB == pBtoA) return pAtoB;
pAtoB = pAtoB->next;
pBtoA = pBtoA->next;
}
return NULL;
}
4、LeetCode142
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode *fast = head, *slow = head;
if (head == NULL) return NULL;
while (fast->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (fast == slow) break;
}
if (fast->next == NULL || fast->next->next == NULL) return NULL;
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
return fast;
}