11.复制带随机指针的链表
typedef struct Node Node;
struct Node* copyRandomList(struct Node* head) {
if(head==NULL)
return NULL;
//1.
Node*cur = head;
while(cur)
{
Node*copy = (Node*)malloc(sizeof(Node));
copy->next=NULL;
copy->random=NULL;
copy->val=cur->val;
Node*next= cur->next;
cur->next= copy;
copy->next=next;
cur=next;
}
//2.处理拷贝节点的random
cur= head;
while(cur)
{
Node*copy = cur->next;
if(cur->random)
copy->random=cur->random->next;
else
copy->random=NULL;
cur=cur->next->next;
}
//3.拆出复制链表
cur=head;
Node*copyhead=head->next;
while(cur)
{
Node*copy=cur->next;
Node*next=copy->next;
cur->next=next;
if(next)
copy->next=next->next;
else
copy->next=NULL;
cur=next;
}
return copyhead;
}
2024.5.5晚上写出的错误代码,但是找不到错误原因
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
typedef struct Node Node;
struct Node* copyRandomList(struct Node* head) {
if (head == NULL)
return NULL;
// 1.
Node*cur=head;
while(cur){
Node*copy=(Node*)malloc(sizeof(Node));
Node*next=cur->next;
cur->next=copy;
copy->next=next;
copy->val=cur->val;
cur=next;
}
// 2.处理拷贝节点的random
cur=head;
copy=cur->next;
next=copy->next;
while(cur){
if (cur->random)
copy->random=cur->random->next;
cur=next;
copy=cur->next;
next=copy->next;
}
// 3.拆出复制链表
cur=head;
copy=cur->next;
next=copy->next;
Node*copyhead=copy;
cur->next=NULL;
while(copy){
copy->next=next->next;
copy=copy->next;
next=copy->next;
}
return copyhead;
}
12.对链表进行插入排序
typedef struct ListNode Node;
struct ListNode* insertionSortList(struct ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
Node*sorthead=head;
Node*cur=head->next;
sorthead->next=NULL;
while(cur){
Node*next=cur->next;
if(cur->val<=sorthead->val)
{
cur->next=sorthead;
sorthead=cur;
}
else
{
Node*sortPrev=sorthead;
Node*sortCur=sortPrev->next;
while(sortCur){
if(cur->val<=sortCur->val){
sortPrev->next=cur;
cur->next=sortCur;
break;
}
else{
sortPrev=sortCur;
sortCur=sortCur->next;
}
}
if(sortCur==NULL){
sortPrev->next=cur;
cur->next=NULL;
}
}
cur=cur->next; //把这个改成cur=cur->next;超时,就不行了,不知道为啥
}
return sorthead;
}
13.删除链表中的重复节点
删除链表中重复的结点_牛客题霸_牛客网 (nowcoder.com)
if(pHead==NULL||pHead->next==NULL)
return pHead;
ListNode*prev=NULL;
ListNode*cur=pHead;
ListNode*next=cur->next;
while(next){
if(cur->val!=next->val){
prev=cur;
cur=next;
next=next->next;
}
else{
while(next&&cur->val==next->val){
next=next->next;
}
if(prev)
prev->next=next;
else
pHead=next; ;
while(cur!=next){
ListNode*del=cur;
cur=cur->next;
free(del);
}
if(next)
next=cur->next;
}
}
return pHead;