题目
中文
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
英文
https://leetcode.com/problems/swap-nodes-in-pairs/
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.
Constraints:
- The number of nodes in the list is in the range
[0, 100]. 0 <= Node.val <= 100
题解
第一次
思路
循环至最后节点为空 两两不停交换。
使用哨兵节点,是头尾不需要特殊化。
代码
struct ListNode *swapPairs(struct ListNode *head){struct ListNode dummyhead;dummyhead.next = head;struct ListNode *temp = &dummyhead;while (temp->next != NULL && temp->next->next != NULL){struct ListNode *node1 = temp->next;struct ListNode *node2 = temp->next->next;struct ListNode *temp1;temp->next=node2;node1->next = node2->next;node2->next = node1;temp = node1;}return dummyhead.next;}
错误点
指针用 ->
直接用.
移动的是指针。
注意其中交换顺序。
这种交换会丢失。
学习
一般方法都是迭代和递归。看到有人使用了哈希表。
迭代还是容易理解,递归不太容易 ,第二次会使用递归来写。
贴一个递归学习的网页。套路解决递归
英文最高票也是 递归。
