// 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) {
if(!head) return head;
ListNode *dummyhead = new ListNode(-1);
dummyhead->next = head;
ListNode *p = dummyhead;
ListNode *pre = head;
ListNode *cur;
ListNode *tmp;
while( p->next && p->next->next){
//
pre = p->next;
cur = pre->next;
tmp = cur->next;
//
pre->next = cur->next;
cur->next = pre;
p->next = cur;
//移动
p = pre;
}
return dummyhead->next;
}
};
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// if(!head) return head;
vector<int> num;
ListNode *dummyhead = new ListNode(-1);
dummyhead->next = head;
ListNode *cur = head;
while(cur){
int val = cur->val;
num.push_back(val);
cur = cur->next;
}
int k = num.size() - n;
cur = dummyhead;
while(k--){
cur =cur->next;
}
cur->next = cur->next->next;
return dummyhead->next;
}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
//快慢指针
ListNode *dummyhead = new ListNode(-1);
dummyhead->next = head;
ListNode *slow = dummyhead;
ListNode *fast = dummyhead;
while(n--){
fast = fast->next;
}
while(fast->next){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyhead->next;
}
};
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *curA = headA,*curB = headB;
int numA = 0, numB = 0;
while(curA){
numA++;
curA = curA->next;
}
while(curB){
numB++;
curB = curB->next;
}
curA = headA,curB = headB;
if(numA < numB){
swap(numA,numB);
swap(curA,curB);
}
int n = numA - numB;
while(n--){
curA = curA->next;
}
while(curA && curB){
if(curA == curB){
return curA;
}
else{
curA = curA->next;
curB = curB->next;
}
}
return NULL;
}
};
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow = head,*fast = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast){
ListNode *tmp1 = fast, *tmp2 = head;
while(tmp1 != tmp2){
tmp1 = tmp1->next;
tmp2 = tmp2->next;
}
return tmp1;
}
}
return 0;;
}
};