链表交换两个node


Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

 

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3

交换相邻两个链表节点。

LeetCode 24. Swap Nodes in Pairs | 交换两个node(链表)


C++版本。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        
        ListNode *tmp=new ListNode(0);
        tmp->next = head;
        ListNode *ans=tmp;
        while(tmp->next && tmp->next->next){
            ListNode *tt = new ListNode(tmp->next->val);
            tmp->next = tmp->next->next;//删除前一个
            tt->next = tmp->next->next;//指向下一对
            tmp->next->next = tt;
            tmp = tmp->next->next;
        }        
        return ans->next;
        
    }
};

 

相关文章:

  • 2021-07-05
  • 2021-06-27
  • 2021-07-12
  • 2021-12-07
  • 2021-05-31
  • 2022-03-10
  • 2021-09-04
猜你喜欢
  • 2021-08-11
  • 2021-09-09
  • 2022-12-23
  • 2021-06-02
  • 2021-09-24
  • 2021-10-31
  • 2022-01-26
相关资源
相似解决方案