链表的好处在于题目好理解,暂时未发现在项目中会有用处
给定1->2->3->4
, 你应该返回2->1->4->3
.
/**
* 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)
{
return head;
}
ListNode list = new ListNode(0);
list.next = head;
head = list;
while (head.next!=null&&head.next.next!=null)
{
ListNode n1 = head.next;
ListNode n2 = head.next.next;
head.next = n2;
n1.next = n2.next;
n2.next = n1;
head = n1;
}
return list.next;
}
}