24. 两两交换链表中的节点
题目链接:24. 两两交换链表中的节点
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;
ListNode *tmp2=cur->next->next->next;
cur->next=cur->next->next;
cur->next->next=tmp1;
cur->next->next->next=tmp2;
cur=cur->next->next;
}
ListNode* result=dummyHead->next;
return result;
}
};
19.删除链表的倒数第N个节点
题目描述:19. 删除链表的倒数第 N 个结点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* cur1=head;
ListNode* dummyhead=new ListNode(0);
dummyhead->next=head;
ListNode* cur2=dummyhead;
for(int i=0;i<n-1;i++)
{
cur1=cur1->next;
}
while(cur1->next)
{
cur1=cur1->next;
cur2=cur2->next;
}
cur2->next=cur2->next->next;
return dummyhead->next;
}
};
面试题 02.07. 链表相交
题目链接:. - 力扣(LeetCode)
链表每个节点只能链接一个节点,所以长链表只需要关注后面部分即可
class Solution {
public:
int getsize(ListNode *node)
{
ListNode* temp1=node;
int size=0;
while(temp1)
{
temp1=temp1->next;
size++;
}
return size;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int len_a=getsize(headA);
int len_b=getsize(headB);
ListNode* a=headA;
ListNode* b=headB;
if(len_a<len_b)
{
swap(a,b);
swap(len_a,len_b);
}
int diff=len_a-len_b;
for(int i=0;i<diff;i++)
{
a=a->next;
}
while(a)
{
if(a==b)
{
return a;
}
a=a->next;
b=b->next;
}
return NULL;
}
};
142.环形链表II
题目链接:. - 力扣(LeetCode)
用哈希表比较简单 ,set容器内不会出现重复的元素
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
set<ListNode*> st;
ListNode* node=head;
while(node!=NULL)
{
if(st.find(node)!=st.end())
return node;
st.insert(node);
node=node->next;
}
return NULL;
}
};
小记
b-a=n,即a,b节点相差n个节点,a移动n步即可到达b节点
for(int i=1;i<=n;i++)
{
cura=cura->next;
}
计算链表size
ListNode* cur=head;
int size=0;
while(cur)
{
size++;
cur=cur->next;
}
删除插入某index的节点,需要将操作节点移动index-1索引的节点
ListNode* cur=dummyHead;
for(int i=0;i<index;i++)
{
cur=cur->next;
}