内容简介:Given a linked list, swap every two adjacent nodes and return its head.You may not modify the values in the list's nodes, only nodes itself may be changed.Example:
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
难度: medium
题目:
给定链表,交换相邻的两个结点并返回其头结点。
不可以修改结点的值,只可以改变结点本身。
思路:加个头结点简化操作。然后就是简单的链表置换。
Runtime: 2 ms, faster than 99.98% of Java online submissions for Swap Nodes in Pairs.
Memory Usage: 26 MB, less than 6.66% of Java online submissions for Swap Nodes in Pairs.
/**
* 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 dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode prev = dummyHead;
ListNode next = prev.next;
while (next != null) {
ListNode nextNext = next.next;
if (nextNext != null) {
prev.next = nextNext;
next.next = nextNext.next;
nextNext.next = next;
}
prev = next;
next = prev.next;
}
return dummyHead.next;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
大数据时代
[英] 维克托•迈尔•舍恩伯格(Viktor Mayer-Schönberger) / 周涛 / 浙江人民出版社 / 2012-12 / 49.90元
《大数据时代》是国外大数据研究的先河之作,本书作者维克托•迈尔•舍恩伯格被誉为“大数据商业应用第一人”,拥有在哈佛大学、牛津大学、耶鲁大学和新加坡国立大学等多个互联网研究重镇任教的经历,早在2010年就在《经济学人》上发布了长达14页对大数据应用的前瞻性研究。 维克托•迈尔•舍恩伯格在书中前瞻性地指出,大数据带来的信息风暴正在变革我们的生活、工作和思维,大数据开启了一次重大的时代转型,并用三......一起来看看 《大数据时代》 这本书的介绍吧!