LeetCode:24. 两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换
示例:
给定1->2->3->4
你应该返回2->1->4->3
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode l1=new ListNode(0);
l1.next=head;
ListNode temp=l1;
if(head==null)
return head;
while(temp.next!=null && temp.next.next!=null){
ListNode second=temp.next;
ListNode third=second.next;
ListNode four=third.next;
temp.next=third;
third.next=second;
second.next=four;
temp=second;
}
return l1.next;
}
}
运用四个指针进行结点的交换