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

【LeetCode】Swap Nodes in Pairs 链表指针的应用

时间:2017-05-19 22:14:49      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:ppa   遍历   next   http   时间复杂度   复杂度   ems   交换   ack   

题目:swap nodes in pairs

<span style="font-size:18px;">/**
 * LeetCode Swap Nodes in Pairs 
 * 题目:输入一个链表,要求将链表每相邻的两个节点交换位置后输出
 * 思路:遍历一遍就可以,时间复杂度O(n)
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
package javaTrain; 

public class Train12 {
	public ListNode swapPairs(ListNode head) {
		if(head == null || head.next == null) return null;
        ListNode pNode;
        pNode = head;
        while(pNode != null && pNode.next != null){
        	int temp; 
        	temp = pNode.val;
        	pNode.val = pNode.next.val;
        	pNode.next.val = temp;
        	pNode = pNode.next.next; 
        }
        return head;
    }
}
</span>


【LeetCode】Swap Nodes in Pairs 链表指针的应用

标签:ppa   遍历   next   http   时间复杂度   复杂度   ems   交换   ack   

原文地址:http://www.cnblogs.com/yfceshi/p/6880279.html

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