leetode24_两两交换链表中的节点
作者:互联网
一、题目
二、算法分析
我主要想着通过while循环自己交换,前面两个单独考虑,后面的都是一样的处理。
因为前面的两个需要交换两次,后面的需要交换三次
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { //如果为空,返回 if( head==NULL ) return head; //如果不为空 ListNode* pre = head; ListNode* lat; ListNode* former=head; int flag = 0; while(pre!=NULL && pre->next != NULL ){ lat = pre->next; //交换节点 //former->next = lat; if(flag==0){ pre->next = lat->next; lat->next = pre; //更新 former = pre; pre = pre->next; //设置头节点 head = lat; flag = 1; } else{ former->next = lat; pre->next = lat->next; lat->next = pre; //更新 former = pre; pre = pre->next; } //更新 //pre = pre->next; //former = pre; } return head; } };
三、参考代码
作者提供的思路很好:
public ListNode swapPairs(ListNode head) { if(head == null || head.next == null){ return head; } ListNode next = head.next; head.next = swapPairs(next.next); next.next = head; return next; }
标签:pre,head,ListNode,next,链表,former,lat,leetode24,节点 来源: https://www.cnblogs.com/fantianliang/p/15528230.html