【LeetCode】C# 24、Swap Nodes in Pairs

来源:互联网 发布:windows清理助手在哪儿 编辑:程序博客网 时间:2024/06/08 12:11

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.

把链表中中的值两两调换。

思路:每两个为一组,定义prev指向被操作组前一个,l1,l2指向两个操作数,next指向下一个。在四个指针结合下完成翻转。
这里写图片描述

/** * Definition for singly-linked list. * public class ListNode { *     public int val; *     public ListNode next; *     public ListNode(int x) { val = x; } * } */public class Solution {    public ListNode SwapPairs(ListNode head) {        if(head==null || head.next==null)            return head;        ListNode fakeHead = new ListNode(5);        fakeHead.next = head;        ListNode l1;        ListNode l2;        ListNode prev = fakeHead;        ListNode ret = head.next;        ListNode next = head;        while(next != null && next.next != null){            l1 = next;            l2 = next.next;            next = next.next.next;            l1.next = next;            l2.next = l1;            prev.next = l2;            prev = l1;        }            return ret;    }}