Swap Nodes in Pairs
程序员文章站
2022-03-05 08:09:29
...
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.
/**
* 递归的两种方法
* @param head
* @return
*/
public static Node SwapNodeByRecursion1(Node head)
{
if(head == null || head.next == null)
return head;
Node n = head.next;
head.next = SwapNodeByRecursion1(head.next.next);
n.next = head;
return n;
}
public Node swapPairsByRecursion2(Node head) {
if (head == null || head.next == null) return head;
Node second = head.next;
Node third = second.next;
second.next = head;
head.next = swapPairsByRecursion2(third);
return second;
}
/**
* 使用迭代的方法
* @param head
* @return
*/
public static Node swapPairsByIterator(Node head)
{
if(head == null || head.next == null) return head;
Node newHead = head.next,a = head,b = a.next,pre = null;
while(a!=null || b!= null)
{
a.next = b.next;
b.next = a;
if(pre != null) pre.next =b;
if(a.next == null) break;
b = a.next.next;
pre = a;
a = a.next;
}
return newHead;
}
上一篇: logback实现分布式系统日志链路追踪
下一篇: web项目中使用多线程的一些坑