关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

牛客网---CM11 链表分割 代码详解+哨兵位的比较

发布时间:2023-06-28 12:01:09

前言


独处未必孤独喜欢就是自由

本章的内容是牛客网随机一题的部分方法的解析

提示:以下是本篇文章正文内容,下面案例可供参考

CM11 链表分割


链接:

CM11 链表分割 link

方法一:尾插(带哨兵位)


1.1 思路:


把小于x的尾插第一个链表,大于x的尾插第二个链表,最后链接在一起

1.2 代码:


class Partition { public:  ListNode* partition(ListNode* pHead, int x)  {  struct ListNode* lesshead,*lesstail,*greaterhead,*greatertail;  lesshead=lesstail=(struct ListNode*)malloc(sizeof(struct ListNode));  greaterhead=greatertail=(struct ListNode*)malloc(sizeof(struct ListNode));  struct ListNode* cur=pHead;  while(cur)  {  if(cur->val<x)  {  lesstail->next=cur;  lesstail=lesstail->next;  }  else  {  greatertail->next=cur;  greatertail=greatertail->next;  }  cur=cur->next;  }  lesstail->next=greaterhead->next;  greatertail->next=NULL;  pHead=lesshead->next;  free(lesshead);  free(greaterhead);  return pHead;  } };

   

1.3 流程图


1.4 注意点


易错点一: lesstail->next=greaterhead->next

这是带哨兵位的链表,所以应该是 lesstail->next=greaterhead->next;而不应该是 lesstail=greaterhead;

易错点二:末尾要置空否则造成循环链表greatertail->next=NULL;

一定要加上greatertail->next=NULL;不然当出现一个链表中既有大于x又有小于x的时候(例如上述流程图7的next指向的还是2如果不置空就会造成循环)

方法二:尾插(不带哨兵位)


2.1代码:


class Partition { public:  ListNode* partition(ListNode* pHead, int x)  {  struct ListNode* lesshead,*lesstail,*greaterhead,*greatertail;  lesshead=lesstail=NULL;  greaterhead=greatertail=NULL;  struct ListNode* cur=pHead;  while(cur)  {  if(cur->val<x)  {  if(lesstail==NULL)  {  lesstail=lesshead=cur;  }  else  {  lesstail->next=cur;  lesstail=lesstail->next;  }  }  else  {  if(greatertail==NULL)  {  greatertail=greaterhead=cur;  }  else  {  greatertail->next=cur;  greatertail=greatertail->next;  }  }  cur=cur->next;  }  if(lesstail==NULL)  {  return greaterhead;  }  else  {  lesstail->next=greaterhead;  }  if(greatertail!=NULL)  {  greatertail->next=NULL;  }  pHead=lesshead;  return pHead;  } };

   

对比:


对比方法一和方法二,很明显带哨兵位可以优化代码减少判断的次数不用考虑头节点是否为空的情况

总结

Ending,今天的内容就到此结束啦,如果后续想了解更多,就请关注我吧


/template/Home/leiyu/PC/Static