/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
struct ListNode *dummy_head = (struct ListNode *)malloc(sizeof(struct ListNode)); // 虚拟头节点
struct ListNode *cur; //当前节点
dummy_head->next = head;
cur = dummy_head;
while(cur->next !=NULL && cur->next->next != NULL)
{
struct ListNode *temp; // 记录临时节点
struct ListNode *temp1;
temp = cur->next;
temp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
temp->next = temp1;
cur = cur->next->next;
}
return dummy_head->next;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode *dummy_head = (struct ListNode *)malloc(sizeof(struct ListNode));
dummy_head->next =head;
struct ListNode *fast = dummy_head;
struct ListNode *slow = dummy_head;;
//n++;
while(n-- && fast != NULL)
{
fast = fast->next;
}
fast = fast->next;
while(fast != NULL)
{
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummy_head->next;
}
leetcode142
环形链表,使用快慢指针
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode *fast = head;
struct ListNode *slow= head;
while(fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
{
struct ListNode *temp1 = fast;
struct ListNode *temp2 = head;
while(temp1 != temp2)
{
temp1 = temp1->next;
temp2 = temp2->next;
}
return temp1;
}
}
return NULL; // 没有找到
}