题目描述:
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
就是成对的交换链表的相邻元素。
比较直接的思路是两次遍历:
第一次遍历使用数据结构存链表节点对(本例使用的是sector类)
第二次遍历节点生成新链表并返回其头指针即可。
/**
* 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;
}
var queue = new Queue<Sector>();
var h = head;
while(h != null){
if(h.next == null){
queue.Enqueue(new Sector(h.val, null));
h = h.next;
}
else{
// there is a lot ,continue make queue
queue.Enqueue(new Sector(h.val, h.next.val));
h = h.next;
h = h.next;
}
}
ListNode result = null;
ListNode r = null;
while(queue.Count > 0){
var s = queue.Dequeue();
if(result == null){
result = s.node2;
r = result;
result.next = s.node1;
result = result.next;
}else{
if(s.node2 != null){
result.next = s.node2;
result = result.next;
result.next = s.node1;
result = result.next;
}
else{
result.next = s.node1;
result = result.next;
}
}
}
return r;
}
public class Sector{
public ListNode node1;
public ListNode node2;
public Sector(int? v1, int? v2)
{
if(v1.HasValue){
node1 = new ListNode(v1.Value);
}
if(v2.HasValue){
node2 = new ListNode(v2.Value);
}
}
}
}