24.两两交换链表中的节点
疑问:只有偶数个节点吗?
答:奇偶数都要考虑在内,有两个判断条件
超时答案,怪了
struct ListNode* swapPairs(struct ListNode* head){
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next = head;
struct ListNode* cur = dummy;
while(cur->next&&cur->next->next)//分别是奇数节点情况与偶数节点情况
{
struct ListNode* temp = cur->next;
struct ListNode* temp1 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
temp = temp1;
cur = cur->next->next;
}
return head;
}
struct ListNode* swapPairs(struct ListNode* head){
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next = head;
struct ListNode* cur = dummy;
while(cur->next&&cur->next->next)//分别是奇数节点情况与偶数节点情况
{
struct ListNode* temp = cur->next;
struct ListNode* temp1 = temp->next;
cur->next = temp1;
temp->next = temp1->next;
temp1->next = temp;
cur = temp;
}
return head;
}
最终结果
return head不行 dummy->next就能过
注意:最后head不指向表头了只能用dummy索引
(根据调试显示cur->next改变dummy->next也改变。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//这里的head指向首元节点
struct ListNode* swapPairs(struct ListNode* head){
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next = head;
struct ListNode* cur = dummy;
while(cur->next&&cur->next->next)//分别是奇数节点情况与偶数节点情况
{
struct ListNode* temp = cur->next;
struct ListNode* temp1 = temp->next;
cur->next = temp1;
temp->next = temp1->next;
temp1->next = temp;
cur = temp;
}
return dummy->next;
}
19.删除链表的倒数第N个节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next = head;
struct ListNode* fast = dummy;
struct ListNode* slow = dummy;
for(int i = 0;i<n;i++)
{
fast = fast->next;
}
while(fast->next)
{
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return dummy->next;
}
160.链表相交
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *l = NULL, *s = NULL;
int lenA = 0, lenB = 0, gap = 0;
s = headA;
while (s) {
lenA ++;
s = s->next;
}
s = headB;
while (s) {
lenB ++;
s = s->next;
}
if (lenA > lenB) {
l = headA, s = headB;
gap = lenA - lenB;
} else {
l = headB, s = headA;
gap = lenB - lenA;
}
while (gap--) l = l->next;
while (l) {
if (l == s) return l;
l = l->next, s = s->next;
}
return NULL;
}
142.环形链表II
再看看
struct ListNode *detectCycle(struct ListNode *head) {
ListNode *fast = head, *slow = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
ListNode *f = fast, *h = head;
while (f != h) f = f->next, h = h->next;
return h;
}
}
return NULL;
}
方法总结
- 虚拟头节点
- 快慢指针