【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.


二、问题分析

题目中明确告诉了不可以修改node的值(要不然。。太easy),那么显然就是链表中节点的交换问题,稍微考虑一下就可以了,无非就是别出现链表的中断即可。为了方便返回最后的head,可以添加一个头结点。

三、Java AC 代码

public ListNode swapPairs(ListNode head) {
        if (head == null || head.next==null) {
			return head;
		}
		ListNode dump = new ListNode(0);
		dump.next = head;
		ListNode pre = dump;
		ListNode cur = head;
		ListNode nxt = head.next;
		while(cur!=null && nxt!=null){
			pre.next = nxt;
			cur.next = nxt.next;
			nxt.next = cur;
			if (cur.next!=null) {
				pre = cur;
				cur = cur.next;
				nxt = cur.next;
			}else {
				break;
			}
			
		}
		return dump.next;
    }



你可能感兴趣的:(java,LeetCode,list)