Swap Nodes in Pairs——LeetCode

时间:2021-03-25 06:37:54

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.

题目大意:给定一个单链表,交换每两个元素。

解题思路:采用头插法重新构建这个链表,每插入两个就把头指针移动到最后,再插入新的节点。

Talk is cheap>>

    public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode res = new ListNode(0);
res = head.next;
ListNode cur = new ListNode(0);
ListNode tmp = head;
ListNode st = head;
int cnt = 1;
while (cur != null && st != null) {
tmp = st.next;
st.next = cur.next;
cur.next = st;
st = tmp;
if (cnt == 2) {
cnt = 0;
cur = cur.next.next;
}
cnt++;
}
return res;
}