您的位置:首页 > Web前端 > Node.js

LeetCode24 Swap Nodes in Pairs 成对交换链表节点

2015-05-06 13:55 639 查看
题目:

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即可。然后继续循环实现交换。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: