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

LeetCode——Swap Nodes in Pairs

时间:2014-07-28 00:28:19      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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.

原题链接:https://oj.leetcode.com/problems/swap-nodes-in-pairs/

题目:给定一个链表,交换两个邻接节点并返回。

你的算法只能使用常数空间。不能修改表中的值,只有节点自身可以改变。

思路:首先,直接交换两个节点的。可以通过,但是不符合要求。

	public ListNode swapPairs(ListNode head) {
		if (head == null || head.next == null)
			return head;
		ListNode back = head;
		while (back != null) {
			if (back.next != null) {
				int val = back.val;
				back.val = back.next.val;
				back.next.val = val;
				back = back.next.next;
			} else
				break;
		}
		return head;
	}


第2种方法:先设置一个虚拟的头节点,防止为空。再交换节点的引用。
	public ListNode swapPairs(ListNode head) {
		ListNode dummy = new ListNode(-1);
		dummy.next = head;
		ListNode pre = dummy;
		while (head != null && head.next != null) {
			ListNode tmp = head.next.next;
			pre.next = head.next;
			head.next.next = head;
			head.next = tmp;
			pre = head;
			head = tmp;
		}
		return dummy.next;
	}



LeetCode——Swap Nodes in Pairs,布布扣,bubuko.com

LeetCode——Swap Nodes in Pairs

标签:leetcode

原文地址:http://blog.csdn.net/laozhaokun/article/details/38168563

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