移除链表元素——虚拟头节点
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
dummyHead->next = head; // 将虚拟头结点指向head,这样方便后面做删除操作
ListNode* cur = dummyHead;
while (cur->next != NULL) {
if(cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
} else {
cur = cur->next;
}
}
head = dummyHead->next;
delete dummyHead;
return head;
}
};
反转链表——双指针
ListNode* reverseList(ListNode* head) {
ListNode* temp; // 保存cur的下一个节点
ListNode* cur = head;
ListNode* pre = NULL;
while(cur) {
temp = cur->next; // 保存一下 cur的下一个节点,因为接下来要改变cur->next
cur->next = pre; // 翻转操作
// 更新pre 和 cur指针
pre = cur;
cur = temp;
}
return pre;
}
两两交换——画图分析,改指向前先保存起来
ListNode* swapPairs(ListNode* head) {
ListNode* dummy_head=new ListNode();
ListNode*temp1=nullptr;
ListNode*temp2=nullptr;
dummy_head->next=head;
ListNode* cur=dummy_head;
while(cur->next&&cur->next->next)
{
temp1=cur->next;
temp2=cur->next->next->next;
cur->next=cur->next->next;
cur->next->next=temp1;
cur->next->next->next=temp2;
cur=cur->next->next;
}
return dummy_head->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) {
ListNode* curA=headA;
ListNode* curB=headB;
int len_A=0 , len_B=0;
while(curA||curB)
{
if(curA)
{
curA=curA->next;
len_A++;
}
if(curB)
{
curB=curB->next;
len_B++;
}
}
curA=headA;
curB=headB;
if(len_A<len_B)
{
int len=len_B-len_A;
while(len--)
{
curB=curB->next;
}
while(curA&&curB)
{
if(curA==curB)return curA;
else
{
curA=curA->next;
curB=curB->next;
}
}
}
else
{
int len=len_A-len_B;
while(len--)
{
curA=curA->next;
}
while(curA&&curB)
{
if(curA==curB)return curA;
else
{
curA=curA->next;
curB=curB->next;
}
}
}
return NULL;
}
};
计算完长度后,重新把头节点赋值给cur