第24题:Swap Nodes in Pairs

来源:互联网 发布:乘联会销量数据 10月 编辑:程序博客网 时间:2024/05/17 01:06

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 maynot modify the values in the list, only nodes itself can be changed.


题目要求:从头结点开始交换每两个相邻节点的值。


编程语言:javascript

解法:算法复杂度为O(n)  思路:注意临界条件。


/** * Definition for singly-linked list. * function ListNode(val) { *     this.val = val; *     this.next = null; * } *//** * @param {ListNode} head * @return {ListNode} */var swapPairs = function(head) {    var copyList = new ListNode(0);    copyList.next = head;            while(head !== null)    {        //两个或两个以下的情况        if( head === null || head.next === null )        {            break;        }        if(head.next.next === null)        {            var temp = head.val;            head.val = head.next.val;            head.next.val = temp;            break;        }            temp = head.val;        head.val = head.next.val;        head.next.val = temp;        head = head.next.next;                if(head.next === null) break;    }    return copyList.next;   };



0 0
原创粉丝点击