本題目來源於:Leetcode:
24.swap nodes in pairs(單鏈表中交換節點對的值)
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.
有兩種思路解決本題:
(1)利用鏈表的特點,改變鏈表指針的指向,改變了節點的位置
package listnode;
/**
* @author Gavenyeah
* @date Start_Time:2016年4月1日 下午4:22:55
* @date End_Time:2016年4月1日 下午4:32:36
*/
public class SwapPairs {
public static void main(String[] args) {
Node head=ListNode.getSingleList();
ListNode.printList(head);
head=new SwapPairs().swapPairs(head);
ListNode.printList(head);
}
public Node swapPairs(Node head) {
Node root=head;
if(head!=null&&head.next!=null){
root=head.next;
Node pre=head;
Node p=null;
Node q=null;
while(head!=null&&head.next!=null){
p=head.next;
q=p.next;
pre.next=p;
p.next=head;
head.next=q;
pre=head;
head=q;
}
}
return root;
}
}
(2)改變相鄰節點對的值,不改變節點指針(通過數組思維實現)
public ListNode swapPairs(ListNode head){
public ListNode swapPairs(ListNode head) {
ListNode p=head;
while(p!=null){
ListNode q=p.next;
if(q!=null){
int temp=p.val;
p.val=q.val;
q.val=temp;
p=p.next;
}
p=p.next;
}
return head;
}
}
代碼中調用的Node類和ListNode類,代碼詳見
Java單鏈表基本操作(一)–順序查找