Open azl397985856 opened 3 years ago
Use a dummy node and iterate the linkedlist.
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
dummy = ListNode(-1)
pre = dummy
first = head
second = head.next
while first and second:
temp = second.next
pre.next = second
second.next = first
first.next = temp
pre = first
first = first.next
second = temp.next if temp else None
return dummy.next
Time complexity: O(n) Space complexity:O(1)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func swapPairs(head *ListNode) *ListNode {
dummyHead := &ListNode{0, head}
temp := dummyHead
for temp.Next != nil && temp.Next.Next != nil {
node1 := temp.Next
node2 := temp.Next.Next
temp.Next = node2
node1.Next = node2.Next
node2.Next = node1
temp = node1
}
return dummyHead.Next
}
idea: recursion. swap the first two nodes. after swaping, link them to the next two swapped nodes by recursion. Time: O(n) Space:O(1)
class Solution {
public ListNode swapPairs(ListNode head) {
if (head==null || head.next == null)
return head;
ListNode curr=head;
ListNode temp=curr;
curr=curr.next;
ListNode next=curr.next;
curr.next=temp;
temp.next=swapPairs(next);
return curr;
}
}
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode current = head;
ListNode pre = new ListNode(0, head);
ListNode res = pre;
ListNode next = head == null ? null: current.next;
while (next != null) {
pre.next = next;
current.next = next.next;
next.next = current;
pre = current;
current = current.next;
next = current == null ? null : current.next;
}
return res.next;
}
}
时间复杂度: O(N) 链表长度 空间复杂度: O(1) 只需要创建一个节点即可。
既然需要交换first和second,那么一成不变的只有first的pre。 所以在head前引入preHead,并使用pre来遍历整个链表。
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode preHead = new ListNode();
preHead.next = head;
ListNode pre = preHead;
while (pre.next != null && pre.next.next != null) {
ListNode first = pre.next;
ListNode second = pre.next.next;
pre.next = second;
first.next = second.next;
second.next = first;
pre = first;
}
return preHead.next;
}
}
Generalized method to swap k nodes in pairs
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0, head), pointer = dummy;
while (pointer != null){
ListNode node = pointer;
for (int i = 0; i < 2 && node != null; i++){
node = node.next;
}
if (node == null) break;
ListNode prev = null, curt = pointer.next, next = null;
for (int i = 0; i < 2; i++){
next = curt.next;
curt.next = prev;
prev = curt;
curt = next;
}
ListNode tail = pointer.next;
tail.next = curt;
pointer.next = prev;
pointer = tail;
}
return dummy.next;
}
}
Time Complexity: O(n), Space Complexity: O(1)
思路:**
不要怕变量多,变量多的话指针才会更加清晰。
就是四个指针,中间两个换位置,头尾用于重新连接
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null)return head;
ListNode prehead = new ListNode();
prehead.next = head;
ListNode first = head;
ListNode ret = first.next;
while(first != null && first.next != null){
ListNode second = first.next;
ListNode behind = second.next;
//逆转
prehead.next = second;
second.next = first;
first.next = behind;
prehead = first;
first = behind;
}
return ret;
}
}
时间复杂度:O(N)
空间复杂度:O(1)
调换next和next.next的位置
var swapPairs = function(head) {
if(!head||!head.next){
return head;
}
let node = new ListNode(0);
node.next = head;
let temp = node;
while(temp.next!==null&&temp.next.next!==null){
let tempNode1 = temp.next;
let tempNode2 = temp.next.next;
temp.next = tempNode2;
tempNode1.next = tempNode2.next;
tempNode2.next = tempNode1;
temp = tempNode1;
}
return node.next;
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* newHead = head->next;
head->next = swapPairs(newHead->next);
newHead->next = head;
return newHead;
}
};
遍历链表,每次遍历2个元素,交换。最后拼接上剩下的单个元素
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode ret = new ListNode(0);
ListNode ret2 = ret;
while(head != null && head.next != null){
ListNode temp = head.next.next;//[3,4]
ret.next = head.next; //[0,2,3,4]
head.next.next = head;//[0,2,1]
head.next = null;//[0,2]
ret = ret.next.next;
head = temp;
}
ret.next = head;
return ret2.next;
}
}
空间复杂度 O(1)
时间复杂度 O(n)
var swapPairs = function (head) {
let dummy = new ListNode(0);
let pre = dummy;
dummy.next = head;
while (head && head.next) {
let next = head.next.next;
pre.next = head.next;
head.next.next = head;
head.next = next;
pre = head;
head = head.next;
}
return dummy.next;
};
时间:O(N) 空间:O(1)
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
模拟穿针引线
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
#写法一 递归
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
# time n
# space 1
# 穿针引线
if not head or not head.next:
return head
newHead = head.next
head.next = self.swapPairs(newHead.next)
newHead.next = head
return newHead
#写法二 迭代
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
# time n
# space 1
# 穿针引线
dummy = ListNode(0, head)
cur = dummy
if not head: return
while cur.next and cur.next.next:
node1 = cur.next
node2 = cur.next.next
cur.next = node2
node1.next = node2.next
node2.next = node1
cur = cur.next.next
return dummy.next
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode preNode = new ListNode(-1, head), res;
preNode.next = head;
res = head.next;
ListNode firstNode = head, secondNode, nextNode;
while(firstNode != null && firstNode.next != null)
{
secondNode = firstNode.next;
nextNode = secondNode.next;
firstNode.next=nextNode;
secondNode.next=firstNode;
preNode.next=secondNode;
preNode=firstNode;
firstNode = nextNode;
}
return res;
}
}
时间复杂度O(N)
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next ==null){
return head;
}
ListNode preNode = new ListNode(-1);
ListNode res;
preNode.next = head;
res = head.next;
ListNode firstNode = head;
ListNode secondNode = head;
ListNode nextNode = head;
while(firstNode !=null && firstNode.next != null){
secondNode = firstNode.next;
nextNode = secondNode.next;
//对链表更新
firstNode.next = nextNode;
secondNode.next = firstNode;
preNode.next = secondNode;
//更新指针位置
preNode = firstNode;
firstNode = nextNode;
}
return res;
}
}
// cur -> qian -> hou
// 交互后
// cur -> hou -> qian
function swapPairs(head: ListNode | null): ListNode | null {
if(!head || !head.next) return head
const newList = new ListNode(0);
newList.next = head
let cur = newList
let qian = null
let hou = null
while(cur.next && cur.next.next){
// 获取前后节点
qian = cur.next
hou = cur.next.next
// 进行交换
cur.next = hou
qian.next = hou.next
hou.next = qian
cur = qian
}
return newList.next
};
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if (not head) or (not head.next):
return head
p1 = head
p2 = head.next
p1.next = self.swapPairs(p2.next)
p2.next = p1
return p2
思考了半天没有想法,参考了答案之后发现recursion 可以很容易解决
Space 和Time complexity 比较难分析
Algo
- should care 4 nodes: A.prev, A, B, B.next
- should have a sentinel
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
# should care 4 nodes: A.prev, A, B, B.next
# should have a sentinel
# corner cases
if not head or not head.next: return head
# prefix the first swap influence to res
res = ListNode(0, head.next)
sentinel = ListNode(0, head)
# iter
while sentinel.next and sentinel.next.next:
# set A, B, B.next
A = sentinel.next
B = sentinel.next.next
B_next = B.next
# A point B.next, B == A.next
A.next = B_next
# B point A
B.next = A
# A.prev point B
sentinel.next = B
# update sentinel
sentinel = A
# return
return res.next
找到反转后的头节点,将上一块的为节点连接到头节点,并将上一块的下一个节点连接到头节点的下一个节点
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1, head);
ListNode pre = dummy, cur = head;
while (cur != null && cur.next != null) {
ListNode next = cur.next;
pre.next = next;
cur.next = next.next;
next.next = cur;
pre = cur;
cur = cur.next;
}
return dummy.next;
}
}
自递归
const swapPairs = head => {
if (!head || !head.next) return head;
let next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
遍历linkedlist,记住下下个node swap 自己和next, 和之前的相连,然后向下下个node转
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
new_head = ListNode(0)
new_head.next = head
prev = new_head
current_node = prev.next
while current_node != None:
next_node = current_node.next
if next_node != None:
temp = next_node.next
next_node.next = current_node
prev.next = next_node
prev = current_node
current_node.next = temp
current_node = temp
else:
break
return new_head.next
time complexity O(n) space complexity O(1)
玩转指针 + dummy head
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode()
dummy.next = head
pre, node = dummy, head
while node and node.next:
pre.next = node.next
next_ = node.next.next
node.next.next = node
node.next = next_
pre = node
node = node.next
return dummy.next
Time: O(n) Space: O(1)
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
进阶:你能在不修改链表节点值的情况下解决这个问题吗?(也就是说,仅修改节点本身。)
后序遍历:后面所有的节点都已经处理好了【后序遍历: 迭代在操作的前面】
def dfs(head):
if not head or not head.next: return head
res = dfs(head.next)
# 主逻辑(改变指针)在进入后面的节点的后面,也就是递归返回的过程会执行到
head.next.next = head
head.next = None
return res
时间on 空间on (递归调用栈)
题解:
var swapPairs = function(head) {
if (head === null|| head.next === null) {
return head;
}
//第二个node是newHead
const newHead = head.next;
//递归newHead.next 表示newHead.next后面的都已经处理好了,旧头接上了,来处理新头(来处理最开始的俩)
head.next = swapPairs(newHead.next);
newHead.next = head;
return newHead;
};
添加一个虚拟头节点,因为head也要被更改
再把这个虚拟头拷贝一份出来, 用作迭代
虚拟头记录新头
内部更改方向
新尾部指向原来的尾部
把虚拟头移动到第二个上面
JavaScript Code:
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
var newhead = new ListNode();
newhead.next = head;
var myhead = newhead;
while(myhead.next !==null && myhead.next.next !== null ){
var fast = myhead.next.next;
var slow = myhead.next;
// start to exchange
myhead.next = fast;
slow.next = fast.next;
fast.next = slow;
myhead = slow;
}
return newhead.next
};
复杂度分析
令 n 为数组长度。
定义虚拟节点、然后 两两节点分别交换
var swapPairs = function (head) {
const newHeader = new ListNode(null, head);
let cur = newHeader;
while (cur.next && cur.next.next) {
const one = cur.next;
const two = cur.next.next;
cur.next = two;
one.next = two.next;
two.next = one;
cur = one;
}
return newHeader.next;
};
因爲第一個listnode會變,所以要引入一個dummy node來遍歷
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
// creat dummy node
ListNode* preHead = new ListNode();
preHead->next = head;
ListNode* temp = preHead;
while (temp->next && temp->next->next) {
ListNode* curr = temp->next;
ListNode* next = temp->next->next;
temp->next = next;
curr->next = next->next;
next->next = curr;
// temp update to the last swapped listnode
temp = curr;
}
return preHead->next;
}
};
迭代法,遍历一遍链表,注意下循环的条件。
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
dummy = ListNode()
dummy.next = head
pre, cur, nxt = dummy, head, head.next
tmp = head
while tmp and nxt:
tmp = nxt.next
nxt.next = cur
cur.next = tmp
pre.next = nxt
if tmp:
pre, cur, nxt = cur, tmp, tmp.next
return dummy.next
时间:O(N) N为链表长度 空间:O(1)
python
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy = prev = ListNode()
prev.next = head
while prev.next and prev.next.next:
a = prev.next
b = prev.next.next
a.next = b.next
b.next = a
prev.next = b
prev = a
return dummy.next
class Solution: def swapPairs(self, head: ListNode) -> ListNode:
Head = ListNode()
Head.next = head
curNode = Head
while curNode and curNode.next and curNode.next.next:
f = curNode
s = curNode.next
t = curNode.next.next
f.next = t
s.next = t.next
t.next = s
curNode = curNode.next.next
return Head.next
Time complexity: O(n)
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
pre, nxt = None, None
first, second = head, head.next
origin_head = second
while second:
nxt = second.next
first.next = nxt
if pre:
pre.next = second
second.next = first
pre = first
first = nxt
if first:
second = first.next
else:
break
return origin_head
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
输入:head = [1,2,3,4] 输出:[2,1,4,3]
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function (head) {
var dh = new ListNode(-1);
dh.next = head;
var cur = dh;
while (cur.next && cur.next.next) {
var next2 = cur.next.next.next;
var next = cur.next;
cur.next = cur.next.next;
cur.next.next = next;
cur.next.next.next = next2;
cur = cur.next.next;
}
return dh.next;
};
N链表的长度
递归,两个node作为一个unit,前面的node的指针指向下一次递归的返回值。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# recursive version
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
first_node = head
second_node = head.next
first_node.next = self.swapPairs(second_node.next)
second_node.next = first_node
return second_node
T: O(N) S: O(N) 递归栈
Go Code:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func swapPairs(head *ListNode) *ListNode {
// base case
if head == nil || head.Next == nil {
return head
}
prev := &ListNode{Next: head}
res := prev
for head != nil && head.Next != nil {
next := head.Next
head.Next = head.Next.Next
next.Next = head
prev.Next = next
head = next
prev = prev.Next.Next
head = head.Next.Next
}
return res.Next
}
复杂度分析
令 n 为数组长度。
递归
func swapPairs(head *ListNode) *ListNode {
if head == nil ||head.Next == nil{
return head
}
res:=head.Next
next:=swapPairs(head.Next.Next)
res.Next = head
head.Next = next
return res
}
复杂度分析
两个数为一组,进行链表的重连,记录最后一个数,做为下一组数的开头
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode last = new ListNode();
ListNode new1 = head.next;
while (head!=null&&head.next!=null){
ListNode next = head.next;
head.next = head.next.next;
next.next = head;
last.next = next;
last= head;
head = head.next;
}
return new1;
}
}
T: O(N) S: O(1)
多画图,找到断开和链接的位置。
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy = ListNode(-1)
dummy.next = head
prev = dummy
while prev.next and prev.next.next:
self.swap(prev)
prev = prev.next.next
return dummy.next
def swap(self, prev):
dummy1 = prev.next
prev.next = dummy1.next
dummy1.next = dummy1.next.next
prev.next.next = dummy1
用递归即可
class Solution {
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;
}
}
# recursion: deal with a pair every time until not head or no head.next
# time: O(N)
# space: O(1)
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next: return head
dummy = ListNode(-1)
dummy.next = head.next
next_batch = head.next.next
head.next.next = head
head.next = self.swapPairs(next_batch)
return dummy.next
day 7 24. 两两交换链表中的节点
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
思路:
1.链表节点的指针,两两交换。定义两个节点的前节点和第二个节点的后续节点,然后逆转。同时改变指针位置。进行下一次交换
2.判断边界条件,为空表和只有一个节点的时候
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:#为空表 或者只有一个节点
return head
ans = ListNode() # A = new 链表新节点
ans.next = head.next# A.next =B
pre = ans # A节点
# 第一个节点 = head
while (head and head.next): #第一个节点不为空且其next不为空
next = head.next# B = A.next
n_next = next.next# Bnext= B.next
# 对链表进行逆转
next.next = head # B.next = A
pre.next = next # A.next = B
head.next = n_next# A.next = Bnext
# 修改指针位置,进行下一轮逆转
pre = head# 前置指针 = 第一个节点 pre -> B-> A-> nextB 指向A
head = n_next # 第一个节点 = 后指针
return ans.next
复杂度:
- 时间复杂度:O(N)
- 空间复杂度:O(1)
语言:C++ 代码: class Solution { public: ListNode swapPairs(ListNode head) { if (head == nullptr || head->next == nullptr) { return head; } ListNode* newHead = head->next; head->next = swapPairs(newHead->next); newHead->next = head; return newHead; } };
iterate or recursion, use dummy head and swap
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode();
ListNode prev = dummy;
dummy.next = head;
while (head != null && head.next != null) {
ListNode next = head.next.next;
prev.next = head.next;
head.next.next = head;
head.next = null;
prev = head;
head = next;
}
return dummy.next;
}
time O(n) space O(1)
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next: return head
new_head = head.next
head.next = self.swapPairs(new_head.next)
new_head.next = head
return new_head
Please note that we want to use a dummy to keep the address of the head because cur is moving towards the end and dummy can finally directly give us head of the list.
class Solution(object):
def swapPairs(self, head):
if not head or not head.next: return head
cur = ListNode(0)
cur.next = head
dummy = cur
while cur.next and cur.next.next:
node1 = cur.next
node2 = cur.next.next
cur.next = node2
node1.next = node2.next
node2.next = node1
# update pointer
cur = node1
return dummy.next
O(n) O(1)
var swapPairs = function(head) {
if(!head||!head.next)return head;
let temp=head.next;
head.next=swapPairs(temp.next);
temp.next=head;
return temp;
};
时间复杂度:O(n),空间复杂度O(1)
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
增加空head节点, head.next 和head next.next交换 前进2个节点 返回时,把空head抛弃
Java Code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
// 增加一个头节点
ListNode preHead = new ListNode();
preHead.next = head;
// 当前指针
ListNode currentNode = preHead;
while(currentNode != null && currentNode.next != null && currentNode.next.next != null){
ListNode f = currentNode;
ListNode s = currentNode.next;
ListNode t = s.next;
// 两两交换链表节点
f.next = t;
s.next = t.next;
t.next = s;
// 当前指针后移两位
currentNode = currentNode.next.next;
}
return preHead.next;
}
}
复杂度分析
令 n 为数组长度。
画图:
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
# 需要比较head, head.next,考虑特殊情况
if not head or not head.next:
return head
dummy = ListNode()
dummy.next = head.next
prev = dummy
A = head
while A and A.next:
B = A.next
nextB = B.next
prev.next = B
B.next = A
A.next = nextB
prev = A
A = nextB
return dummy.next
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode dum = new ListNode(0);
dum.next = head;
ListNode temp = dum;
while(temp.next != null && temp.next.next != null){
//声明两个指针start,end
ListNode start = temp.next;
ListNode end = temp.next.next;
temp.next = end;
start.next = end.next;
end.next = start;
//移动指针
temp = start;
}
return dum.next;
}
}
时间复杂度:O(n)
空间复杂度:O(1)
迭代法
# 迭代
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
virtualhead = ListNode()
virtualhead.next = head
pre = virtualhead
while head and head.next:
next = head.next
nnext = next.next
#修改指针
pre.next = next
next.next = head
head.next = nnext
#更新节点
pre = head
head = nnext
return virtualhead.next
时间复杂度: O(N)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head||!head -> next) return head;
ListNode* std = new ListNode(0); //增加一个哨兵节点
std -> next = head;
ListNode* first = head;
ListNode* second = nullptr;
ListNode* new_head = first -> next;
while(first&&first -> next){
second = first -> next;
first -> next = second -> next;
second -> next = first;
std -> next = second;
std = first;
first = first -> next;
}
return new_head;
}
};
// leetcode 24. 两两交换链表中的节点 // 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 // 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
1,迭代法:关键是高清如何交换两个相邻节点,然后迭代交换即可。
# include <stdio.h>
# include <iostream>
# include <vector>
# include <stack>
using namespace std;
// 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 == nullptr) return nullptr;
else if(head->next == nullptr) return head;
ListNode* temp = new ListNode(-1);
temp ->next = head;
ListNode* pre = temp;
while(pre->next != nullptr && pre->next->next != nullptr) {
ListNode* cur = pre->next;
ListNode* next = pre->next->next;
pre->next = cur->next;
cur->next = next->next;
next->next = cur;
pre = cur;
}
return temp->next;
}
};
Three pointers, need to have a dummy point that can point to the new header in order to return the new header Interesting thing about three pointers in linked list is that, different with three pointers in array, those three pointers can have relations so that when you move, you can only define the first pointer, the 2nd and 3rd pointers would just be first.next and first.next.next
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
//boundary
if (head == null || head.next == null){
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
while (head != null && head.next != null && head.next.next != null){
ListNode p1 = head.next;
ListNode p2 = head.next.next;
//swap
p1.next = p2.next;
p2.next = p1;
head.next = p2;
head = p1;
}
return dummy.next;
}
}
【思路】递归 如果只剩自己(没有next)或者自己是null,就return 自己 因为没有旋转的条件了。然后把return的值【已经换好的后面list的头】,放在第一个的后面,第二个.next=第一个, 把第二个return回去就好了 【复杂度】 遍历一遍,所以是O(n)
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode first = head;
ListNode second = head.next;
ListNode next = second.next;
ListNode firstNext = swapPairs(next);
second.next = first;
first.next = firstNext;
return second;
}
Set one more head in front of the original list,loop over the list and swap the nodes.
JavaScript
var swapPairs = function(head) {
if (!head || head.next === null) {
return head;
}
let newHead = new ListNode(0);
newHead.next = head;
let temp = newHead;
while(temp.next && temp.next.next) {
const node1 = temp.next;
const node2 = temp.next.next;
temp.next = node2;
node1.next = node2.next;
node2.next = node1;
temp = node1;
}
return newHead.next
};
24. 两两交换链表中的节点
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
前置知识
题目描述
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4] 输出:[2,1,4,3] 示例 2:
输入:head = [] 输出:[] 示例 3:
输入:head = [1] 输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内 0 <= Node.val <= 100