描述: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.
在这里我把我自己的代码贴出来,我感觉代码不是很简洁,如果有更方便的方法,希望大家提意见。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode p,q,s,t;
q = head;
p = head.next;
if(p.next == null || p.next.next == null){
head = p;
}
int count = 0;
while(p.next != null && p.next.next != null){
s = p.next;
q.next = s;
p.next = q;
t = q;
if(count==0)
head = p;
count++;
q = s;
p = q.next;
t.next = p;
}
t = p.next;
p.next = q;
q.next = t;
return head;
}
}
在这里我觉得在边界问题上有点复杂,关于边界问题可能会出现这些情况:
head = null 或者head链表中只有一个元素,这两种情况不需要做任何操作,直接返回head;当链表中元素为2个或者3个的时候,这种情况也需要单独处理;我觉得对这种情况单独处理未免太复杂了,造成这种复杂问题可能跟链表没有头结点有关吧,这里我就采用上面的这种比较笨的方法,分开出来不同的情况。