题:https://leetcode.com/problems/swap-nodes-in-pairs/description/
题目
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list’s nodes, only nodes itself may be changed.
题目大意
将链表中 相邻的结点 进行交换。
要求space n(1)。
思路
因为需要改变头结点所以使用了一个辅助头结点。使得代码更一致,无需 特别 处理 头结点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode nhead = new ListNode(0);
nhead.next = head;
ListNode fp = nhead;
while(fp.next!=null && fp.next.next!= null){
ListNode sp = fp.next;
ListNode tp = fp.next.next;
sp.next = tp.next;
tp.next = sp;
fp.next = tp;
fp = fp.next.next;
}
return nhead.next;
}
}
看了 答案的写法 基本一致,现在主要的突破点是 提升 coding 速度。