{
  "type": "code_options",
  "author": "https://github.com/qiyuangong/leetcode",
  "source": "solution.md",
  "exercise_id": "1adcc2813fb04141b5bc11a3f7dc88f0",
  "keywords": "递归,链表",
  "title": "两两交换链表中的节点",
  "desc": [
    {
      "content": "\n<p>给定一个链表，两两交换其中相邻的节点，并返回交换后的链表。</p><p><strong>你不能只是单纯的改变节点内部的值</strong>，而是需要实际的进行节点交换。</p><p> </p><p><strong>示例 1：</strong></p><img alt=\"\" src=\"https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/images/swap_ex1.jpg\" style=\"width: 422px; height: 222px;\" /><pre><strong>输入：</strong>head = [1,2,3,4]<strong><br />输出：</strong>[2,1,4,3]</pre><p><strong>示例 2：</strong></p><pre><strong>输入：</strong>head = []<strong><br />输出：</strong>[]</pre><p><strong>示例 3：</strong></p><pre><strong>输入：</strong>head = [1]<strong><br />输出：</strong>[1]</pre><p> </p><p><strong>提示：</strong></p><ul>\t<li>链表中节点的数目在范围 <code>[0, 100]</code> 内</li>\t<li><code>0 <= Node.val <= 100</code></li></ul><p> </p><p><strong>进阶：</strong>你能在不修改链表节点值的情况下解决这个问题吗?（也就是说，仅修改节点本身。）</p>",
      "language": "markdown"
    }
  ],
  "answer": [
    {
      "content": "",
      "language": "python"
    }
  ],
  "prepared": [
    [
      {
        "content": "",
        "language": "python"
      }
    ],
    [
      {
        "content": "",
        "language": "python"
      }
    ],
    [
      {
        "content": "",
        "language": "python"
      }
    ]
  ],
  "template": {
    "content": "class ListNode(object):\n\tdef __init__(self, x):\n\t\tself.val = x\n\t\tself.next = None\nclass LinkList:\n\tdef __init__(self):\n\t\tself.head=None\n\tdef initList(self, data):\n\t\tself.head = ListNode(data[0])\n\t\tr=self.head\n\t\tp = self.head\n\t\tfor i in data[1:]:\n\t\t\tnode = ListNode(i)\n\t\t\tp.next = node\n\t\t\tp = p.next\n\t\treturn r\n\tdef\tconvert_list(self,head):\n\t\tret = []\n\t\tif head == None:\n\t\t\treturn\n\t\tnode = head\n\t\twhile node != None:\n\t\t\tret.append(node.val)\n\t\t\tnode = node.next\n\t\treturn ret\nclass Solution(object):\n\tdef swapPairs(self, head):\n\t\tdummyHead = ListNode(-1)\n\t\tdummyHead.next = head\n\t\tprev, p = dummyHead, head\n\t\twhile p != None and p.next != None:\n\t\t\tq, r = p.next, p.next.next\n\t\t\tprev.next = q\n\t\t\tq.next = p\n\t\t\tp.next = r\n\t\t\tprev = p\n\t\t\tp = r\n\t\treturn dummyHead.next\n# %%\nl = LinkList()\nhead = [1,2,3,4]\nl1 = l.initList(head)\ns = Solution()\nprint(l.convert_list(s.swapPairs(l1)))",
    "language": "python"
  },
  "node_id": "dailycode-a23959a66506488a952c2aace7627c39",
  "license": "csdn.net",
  "created_at": 1637894159,
  "topic_link": "https://bbs.csdn.net/topics/600470117"
}