反转链表II
struct ListNode*reverse(struct ListNode** head2)//反转部分链表(头插法)
{
if(*head2==NULL)
{
return NULL;
}
struct ListNode*p=NULL;
struct ListNode*p1=*head2;
struct ListNode*p2=(*head2)->next;
while(p1)
{
p1->next=p;
p=p1;
p1=p2;
if(p2)
{
p2=p2->next;
}
}
return p;
}
struct ListNode* reverseBetween(struct ListNode* head, int left, int right){
if(head==NULL)
{
return NULL;
}
if(head->next==NULL)
return head;
int i=0;
struct ListNode*tail=head;
struct ListNode*copy_tail=tail;
struct ListNode*copy_tail2=tail;
for(i=1;i<right;i++)
{
tail=tail->next;
}
copy_tail=tail->next;
tail->next=NULL;
struct ListNode*newhead=(struct ListNode*)malloc(sizeof(struct ListNode));
newhead->next=head;
for(i=0;i<left;i++)
{
copy_tail2=newhead;
newhead=newhead->next;
}
struct ListNode*p2=reverse(&newhead);
copy_tail2->next=p2;
newhead->next=copy_tail;
if(left==1)//考虑特殊情况(这里也需要多次画图)
return p2;
return head;
}
目前没学C++,数据结构也是略知一二,当作是一次做题记录吧。
复制带随机指针的链表
struct Node* copyRandomList(struct Node* head)
{
if (head == NULL)
return NULL;
struct Node* tail = head;
while (tail)
{
struct Node* copy = (struct Node*)malloc(sizeof(struct Node));
copy->next = tail->next;
tail->next = copy;
copy->val=tail->val;
tail = tail->next->next;
}
tail=head->next;
struct Node*prev_tail=head;
while(tail)
{
tail->random = prev_tail->random==NULL?NULL:prev_tail->random->next;
tail=tail->next==NULL?NULL:tail->next->next;
prev_tail=prev_tail->next->next;
}
struct Node* tail2 = head;
struct Node* copy_list =(struct Node*)malloc(sizeof(struct Node));
struct Node* res=copy_list;
//copy_list->next=NULL;
while(tail2)//&©_list)
{
tail2=tail2->next;
copy_list->next=tail2;
tail2=tail2->next;
copy_list=copy_list->next;//这个地方要注意!!!
}
copy_list= NULL;
return res->next;
}
中间有个地方卡了好久。。。最后得出写代码不能老想着偷懒,哈哈哈