码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Swap Nodes in Pairs

时间:2014-07-08 20:40:15      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   java   color   os   

题目:给定一个单链表,要求对链表每两两节点进行交换,例子: 1->2->3->4, 交换后 2->1->4->3.

算法:链表操作,设置4个指针

pre:左边界,维护交换后链表的结构

swapA:指向要交换的第一个节点

swapB:指向要交换的第二个节点

post:右边界,维护交换后链表的结构


链表:...->1->2->3->4

对应:pre  swapA  swapB  post

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
	        if (null == head) {
	        	return null;
	        }
	    	
	    	ListNode pre = head;
	        ListNode post = null;
	        ListNode swapA = head;
	        ListNode swapB = null;
	        while (null != pre) {
	        	if (head == pre) {
	        		// begin with the list head
	        		if (null != pre.next) {
	        			swapA = pre;
	        			swapB = swapA.next;
	        			post = swapB.next;
	        			
	        			// swap node pair
	        			swapA.next = post;
	        			swapB.next = swapA;
	        			head = swapB;
	        		} else {
	        			break;
	        		}
	        	} else {
//	        		pre = swapA;  // after swap
	        		if (null != pre.next) {
		        		swapA = pre.next;
		        		if (null != swapA.next) {
		        			swapB = swapA.next;
		        			post = swapB.next;
		        			
		        			// swap node pair
		        			pre.next = swapB;
		            		swapB.next = swapA;
		            		swapA.next = post;
		        		} else {
		        			break;  // last one node, don't swap
		        		}
		        	} else {
		        		break;  // end of the list
		        	}
	        	}
	        	
	        	pre = swapA;  // after swap
	        }
	        
	        return head;
	    }
}


[LeetCode]Swap Nodes in Pairs,布布扣,bubuko.com

[LeetCode]Swap Nodes in Pairs

标签:des   style   blog   java   color   os   

原文地址:http://blog.csdn.net/yeweiouyang/article/details/37532101

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!