将给定的链表中每两个相邻的节点交换一次,返回链表的头指针
例如,
给出1->2->3->4,你应该返回链表2->1->4->3。
你给出的算法只能使用常量级的空间。你不能修改列表中的值,只能修改节点本身。
public class Solution60 { public ListNode swapPairs(ListNode head) { if(head==null||head.next==null) { return head; } //先将原来的链表交错分开成为两个链表 ListNode cur1= head; ListNode cur2 = head.next; while(cur1!=null&&cur1.next!=null) { ListNode secound = cur1.next; cur1.next = secound.next; secound.next = secound.next==null?null:secound.next.next; cur1=cur1.next; } //然后将两个链表在合并到一起 ListNode cur3 = head; ListNode cur4 = cur2; while(cur3!=null&&cur4!=null){ ListNode cur3Next = cur3.next; ListNode cur4Next = cur4.next; cur4.next = cur3; cur4=cur4Next; cur3.next=cur4; cur3=cur3Next; } //如果是奇数后面需要在加一位 if(cur1!=null){ ListNode node = cur2; while(node.next!=null){ node = node.next; } node.next = cur1; } return cur2; } }
public class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; } ListNode dummy = new ListNode(0); ListNode cur = head; ListNode pre = dummy; while (cur != null && cur.next != null) { ListNode pNext = cur.next; cur.next = pNext.next; pNext.next = cur; pre.next = pNext; pre = cur; cur = cur.next; } return dummy.next; } }
public class Solution { public ListNode swapPairs(ListNode head) { if(head == null || head.next == null) return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode tmp, pre = dummy, cur = head; while(cur != null && cur.next != null){ tmp = cur.next; cur.next = tmp.next; tmp.next = pre.next; pre.next = tmp; pre = cur; cur = cur.next; } return dummy.next; } }
public class Solution { public ListNode swapPairs(ListNode head) { if(head==null||head.next==null)return head; ListNode p = new ListNode(0); ListNode result = p; p.next=head; ListNode p1=head; while(p1!=null&&p1.next!=null){ //以下为交换相邻两个节点,实则考虑两个节点和前后各一个节点的指针问题 // 相当于每一次循环对四个节点进行处理 ListNode p2=p1.next; ListNode temp = p2.next; p.next=p1.next; p2.next=p1; p1.next=temp; //调整指针位置为了进入下一次循环 p=p.next.next; p1=p.next; } //针对while中没处理的尾部剩一个节点的情况进行处理 if(p1!=null){ p1.next=null; } return result.next; } }
public class Solution { public ListNode swapPairs(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode cur = dummy; ListNode next = cur.next; while(next != null && next.next != null) { cur.next = next.next; next.next = cur.next.next; cur.next.next = next; cur = next; next = next.next; } return dummy.next; } }
public class Solution { public static ListNode swapPairs(ListNode head) { if(head == null || head.next == null) return head; ListNode dummy = new ListNode(0); dummy.next = head; for (ListNode pre = dummy, cur = head, temp; cur != null && cur.next != null; pre = cur, cur = cur.next) { temp = cur.next; cur.next = temp.next; temp.next = pre.next; pre.next = temp; } return dummy.next; } }