Swap Nodes in Pairs(easy)

来源:互联网 发布:巫妖王之怒3.35数据库 编辑:程序博客网 时间:2024/04/27 02:26

题目

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.

题意

     将链表临接的元素交换

分析

     每次读两个节点插入新链表,因为是指针操作,不占用额外空间。最后需要把tail指针的next设为NULL。例如链表为p1->p2->p3->p4的情况,如果最后不修改p3->next,那么就会出现一个环:p2->p1->p4->p3->p4->...

就是每次跳两个节点,后一个接到前面,前一个接到后一个的后面,最后现在的后一个(也就是原来的前一个)接到下下个结点(如果没有则接到下一个)

这道题中用了一个辅助指针作为表头,这是链表中比较常用的小技巧,因为这样可以避免处理head的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧,大家以后会经常遇到。
因为这是一遍过的算法,时间复杂度明显是O(n),空间复杂度是O(1)。

实现

public ListNode swapPairs(ListNode head) {    if(head == null)        return null;    ListNode helper = new ListNode(0);    helper.next = head;    ListNode pre = helper;    ListNode cur = head;    while(cur!=null && cur.next!=null)    {        ListNode next = cur.next.next;        cur.next.next = cur;        pre.next = cur.next;        if(next!=null && next.next!=null)            cur.next = next.next;        else            cur.next = next;        pre = cur;        cur = next;    }    return helper.next;}


0 0
原创粉丝点击