欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > 链表的操作-反转链表

链表的操作-反转链表

2025/5/16 4:11:06 来源:https://blog.csdn.net/qq_45265769/article/details/146965935  浏览:    关键词:链表的操作-反转链表

链表

160相交链表

在这里插入图片描述

代码

class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {ListNode* h1=headA;ListNode* h2=headB;while(h1&&h2){if(h1!=h2){h1=h1->next;h2=h2->next;}else{return h1;}}if(h1==nullptr){h1=headB;}else{h2=headA;}while(h1&&h2){if(h1!=h2){h1=h1->next;h2=h2->next;}else{return h1;}}if(h1==nullptr){h1=headB;}else{h2=headA;}while(h1&&h2){if(h1!=h2){h1=h1->next;h2=h2->next;}else{return h1;}}return nullptr;}
};

代码优化

通过两次遍历,headA,headB走的距离一定是一样的。
最终只会出现两种情况:

  1. 相等指向同一个ListNode,
  2. 两个链表中没有相交的点,又因为最后指向的都是空指针
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {ListNode* h1=headA;ListNode* h2=headB;while(h1!=h2){h1=(h1==nullptr)?headB:h1->next;h2=(h2==nullptr)?headA:h2->next;}return h1;}

其他方法

  1. 记录长度,这个办法好像没办法解决,因为你不知道长度在那?
  2. 通过map,set存放ListNode,然后边遍历,边计算是否存在

反转链表

  1. 方法1:
    ListNode* reverseList(ListNode* head) {ListNode* pre=nullptr;ListNode* cur=head;while(cur){ListNode* ne=cur->next;cur->next=pre;pre=cur;cur=ne;}return pre;}

方法2:

 ListNode* reverseList(ListNode* head) {ListNode* pre=new ListNode(-1);ListNode* cur=head;while(cur){ListNode* ne=cur->next;cur->next=pre->next;pre->next=cur;cur=ne;}ListNode* t=pre->next;delete pre;return t;}

递归的方法

ListNode* reverseList(ListNode* head) {if(head==nullptr||head->next==nullptr){return head;}ListNode* last=reverseList(head->next);head->next->next=head;head->next=nullptr;return last;}
e* last=reverseList(head->next);head->next->next=head;head->next=nullptr;return last;}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词