Swap Nodes in Pairs -- leetcode

原创 2016年08月30日 16:33:07

题目描述:
Given a linked list, swap every two adjacent nodes and return its head.

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

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

大意是:成对的交换链表的结点,1和2交换;3和4交换,5和6交换等。

/**
 * 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) {
        if (head == NULL || head->next == NULL) return head;
        ListNode *newList = new ListNode(0);
        newList->next = head;
        head = newList;
       while(head->next != NULL && head->next->next != NULL){
           ListNode *p1 = head -> next;//取出第一个节点结点 
           ListNode *p2 = head -> next -> next;//取出第二个节点结点
           // head->p1->p2->...  ---->> head->p2->p1->...
           head -> next = p2;
           p1 -> next = p2 -> next;
           p2 -> next = p1;
           //move head to p1
           head = p1;
       }
       return newList->next;
    }
};
版权声明:本文为博主原创文章,欢迎转载,请注明出处。

LeetCode Swap Nodes in Pairs

题目: Given a linked list, swap every two adjacent nodes and return its head. For example, Gi...

LeetCode之24----Swap Nodes in Pairs

题目: Given a linked list, swap every two adjacent nodes and return its head. For example, Gi...

[leetcode: Python]24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.For example, Given 1->2->3->...
  • NXHYD
  • NXHYD
  • 2017年05月19日 15:37
  • 220

leetcode-24 Swap Nodes in Pairs

问题描述地址:https://leetcode.com/problems/swap-nodes-in-pairs/ 描述: Given a linked list, swap every two...

LeetCode:Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3-...
  • wyc1230
  • wyc1230
  • 2012年02月16日 12:36
  • 1531

LeetCode OJ-24-Swap Nodes in Pairs

题目:Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2...

关于LeetCode中Swap Nodes in Pairs一题的理解

题目如下: Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1-...

LeetCode-24.Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3-...

[C++]LeetCode: 109 Swap Nodes in Pairs (交换相邻节点位置)

题目: Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->...

LeetCode Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.For example, Given 1->2->3->...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Swap Nodes in Pairs -- leetcode
举报原因:
原因补充:

(最多只允许输入30个字)