两两交换链表中的节点
一开始有错误,找不出来,但是gdb真好用
-
Definition for singly-linked list.
-
struct ListNode {
-
int val;
-
ListNode *next;
-
ListNode() : val(0), next(nullptr) {}
-
ListNode(int x) : val(x), next(nullptr) {}
-
ListNode(int x, ListNode *next) : val(x), next(next) {}
-
};
/
class Solution {
public:
ListNode swapPairs(ListNode* head) {
ListNode *dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode *cur = dummyhead;
while(cur->next && cur->next->next)
{
ListNode tmp1 = cur->next->next->next;
ListNode tmp2 = cur->next;
cur->next = cur->next->next;
cur->next->next = tmp2;
cur->next->next->next = tmp1;
cur = cur->next->next;
}
return dummyhead->next;
}
};
删除倒数第N个节点
一开始没有考虑到删除最后一个节点
/ -
Definition for singly-linked list.
-
struct ListNode {
-
int val;
-
ListNode *next;
-
ListNode() : val(0), next(nullptr) {}
-
ListNode(int x) : val(x), next(nullptr) {}
-
ListNode(int x, ListNode *next) : val(x), next(next) {}
-
};
/
class Solution {
public:
ListNode removeNthFromEnd(ListNode* head, int n) {
ListNode *dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode *p = dummyhead;
ListNode q = p;
for(int i = 0; i < n; ++i)
{
q = q->next;
}
while(q->next)
{
p = p->next;
q = q->next;
}
ListNode tmp = p->next;
if(n == 1)
{
p->next =nullptr;
}
else
{
p->next = p->next->next;
}
delete tmp;
return dummyhead->next;
}
};
链表相交
/ -
Definition for singly-linked list.
-
struct ListNode {
-
int val;
-
ListNode *next;
-
ListNode(int x) : val(x), next(NULL) {}
-
};
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == NULL || headB == NULL)
{
return NULL;
}
ListNode *cur = headA;
int len1 = 0;
int len2 = 0;
while(cur)
{
len1++;
cur = cur->next;
}
cur = headB;
while(cur)
{
len2++;
cur = cur->next;
}
ListNode *p = headA;
ListNode *q = headB;
if(len1 > len2)
{
int len = len1 -len2;
for(int i = 0; i < len; ++i)
{
p = p->next;
}
}
else
{
int len = len2 - len1;
for(int i = 0; i < len; ++i)
{
q = q->next;
}
}
while(p && p != q)
{
p = p->next;
q = q->next;
}
return p;}
};
环形链表
/**
-
Definition for singly-linked list.
-
struct ListNode {
-
int val;
-
ListNode *next;
-
ListNode(int x) : val(x), next(NULL) {}
-
};
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *p = head;
ListNode *q = head;while(q && q->next) { p = p->next; q = q->next->next; if(q == p) { ListNode *p1 = head; ListNode *q1 = q; while(p1 != q1) { p1 = p1->next; q1 = q1->next; } return p1; } } return nullptr;
}
};