题目:
Given a linked list, swap every two adjacent nodes and return its head.
For example,Given1->2->3->4, you should return the list as2->1->4->3.
Your algorithm should use only constant space. You maynotmodify 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即可。然后继续循环实现交换。
以诚感人者,人亦诚而应。