题目:
给定一个链表, 两两交换其中相邻的节点, 并返回交换后的链表.
你不能只是单纯的改变节点内部的值, 而是需要实际的进行节点交换.
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
解题思路:
设置三个指针, 分别指向前后和当前节点.
- class Solution {
- public ListNode swapPairs(ListNode head) {
- if(head==null)
- return head;
- ListNode preHead=new ListNode(-1);
- preHead.next=head;
- ListNode left=preHead;
- ListNode mid=head;
- if(head.next==null)// 如果只有一个节点, 直接返回这个节点
- return head;
- ListNode right=head.next;
- while(mid!=null&&mid.next!=null){
- mid.next=right.next;
- right.next=mid;
- left.next=right;
- left=mid;
- mid=left.next;
- if(mid!=null)
- right=mid.next;
- }
- return preHead.next;
- }
- }
来源: http://www.bubuko.com/infodetail-2975268.html