考研算法
题目
题目要求
合并链表+反转列表
C++代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void rearrangedList(ListNode* head) {
if (head->next==NULL) return ;
int len=0;
auto p=head;
while(p)
{
len++;
p=p->next;
}
if (len==1)
{
return ;
}
int mid=(len+1)/2;
auto a=head;
for (int i=0;i<mid-1;i++)
{
a=a->next;
}
auto b=a->next;
auto c=b->next;
a->next=NULL;
b->next=NULL;
while(c)
{
auto t=c->next;
c->next=b;
b=c;
c=t;
}
for (auto p=head,q=b;q;)
{
auto temp=q->next;
q->next=p->next;
p->next=q;
p=p->next->next;
q=temp;
}
}
};
知识点
先将链表从中间分为左右两个链表,再将右链表反转,最后将两个链表合并
反转列表
int mid=(len+1)/2;
auto a=head;
for (int i=0;i<mid-1;i++)//寻找左链表结束点
{
a=a->next;
}
auto b=a->next;
auto c=b->next;
a->next=NULL;//需要设置为null,让它断开连接,否则最后的循环无法退出
b->next=NULL;//需要设置为null,让它断开连接,否则最后的循环无法退出
while(c)//反转
{
auto t=c->next;
c->next=b;
b=c;
c=t;
}
合并链表
for (auto p=head,q=b;q;)//合并
{
auto temp=q->next;
q->next=p->next;
p->next=q;
p=p->next->next;
q=temp;
}
python代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rearrangedList(self, node):
"""
:type node: ListNode
:rtype: void
"""
if node.next==None :return 0
le=0;
p=node
while(p):
p=p.next
le=le+1
mid=(le+1)//2
a=node
for i in range(mid-1):
a=a.next
b=a.next
c=b.next
a.next=None
b.next=None
while(c):#反转
p=c.next
c.next=b
b=c
c=p
x=node
z=b
while(z): #合并
t=z.next
z.next=x.next
x.next=z
x=x.next.next
z=t