LeetCode 24. Swap Nodes in Pairs 解题报告

来源:互联网 发布:derwent专利数据库 编辑:程序博客网 时间:2024/06/07 05:11

24. Swap Nodes in Pairs

My Submissions
Total Accepted: 82451 Total Submissions: 239340 Difficulty: Medium

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.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


    一道链表的题目,考验对指针的理解。大四那年去小米三面的时候KK考了我两道题,其中一道就是这个,至今记忆犹新。今天重做一遍。虽然当时KK肯定了我的code,但如今看来,还是有小bug的。。。。。

    我的AC代码

public class SwapNodesinPairs {/** * @param args */public static void main(String[] args) {ListNode h = new ListNode(1);ListNode h2 = new ListNode(2);ListNode h3 = new ListNode(3);ListNode h4 = new ListNode(4);h.next = h2;h2.next = h3;h3.next = h4;System.out.print(swapPairs(h));}public static ListNode swapPairs(ListNode head) {if (head == null || head.next == null)return head;ListNode h = new ListNode(0);h.next = head;ListNode pre = h, p1 = head, p2 = head.next;while (p1 != null && p2 != null) {// swappre.next = p2;p1.next = p2.next;p2.next = p1;// 指针后移pre = p1;p1 = p1.next;if (p1 != null)p2 = p1.next;}return h.next;}}


1 0
原创粉丝点击