标签:java leetcode java 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.
翻译:
给你一个链表,交换每两个相连的节点。
思路:
就是节点交换问题。只要保存头结点,且要理清交换的节点的位置问题。
代码:
public ListNode swapPairs(ListNode head) {
	     ListNode root = new ListNode(0);//创建个首节点指向链表开始
	     root.next = head;
	     ListNode pre = root;//前一个节点
	     while(head!=null && head.next!=null)
	     {
	    	 ListNode t = head.next.next;
	    	 pre.next = head.next;
	    	 pre.next.next = head;
	    	 head.next = t;
	    	 pre = head;
	    	 head = t;
	    	 
	     }
	     return root.next;
	    }
接着就是交换问题。 假设 现在的链表是1->2->3->4 。首先创建个root节点,他的next指向头部。
第一次循环:pre指向root,head指向1,要交换12,首先的保存2的下一个节点3,用t表示,接着使得pre的next为2 ,即head的next;接着2的下一个节点为1,于是乎pre.next.next = head.最后head的下一个为3,即head.next = t。
此时链表为2-1-3-4.此时使得指针跳2个。即pre指向1,head指向3即可。然后继续循环实现交换。
LeetCode24 Swap Nodes in Pairs 成对交换链表节点
标签:java leetcode java leetcode 解题代码 算法
原文地址:http://blog.csdn.net/vvaaiinn/article/details/45535005