题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例
给定 1->2->3->4, 你应该返回 2->1->4->3.
思路
这是个基本的链表题目,思路很好想,结果我写出来发现并不是那么回事。我采用三个节点pre、cur、next依此对链表进行处理,这里有个小技巧,我们new一个pre用来保存一个额外的节点,最后返回时返回pre.next即可,不用再去操心在不断变换位置中,头节点不知所踪。
代码
public class problem24 {
//Definition for singly-linked list.
public static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode swapPairs(ListNode head) {
//特殊情况判断
if(head==null) return null;
if(head.next==null) return head;
//三个指针进行反序操作
ListNode pre=new ListNode(0);
ListNode cur=head;
ListNode next=cur.next;
ListNode re=pre;//保存头节点,最后返回re.next即可
while(cur!=null&&cur.next!=null){
// System.out.println("cur:"+cur.val);
cur.next=next.next;
next.next=cur;
pre.next=next;
pre=cur;
cur=cur.next;
//长度是偶数时会出现cur是null的情况,所以添加if进行判断,以免报错
if(cur!=null&&cur.next!=null) next=cur.next;
}
return re.next;
}
public static void main(String[] args) {
ListNode a=new ListNode(1);
a.next=new ListNode(2);
a.next.next=new ListNode(3);
a.next.next.next=new ListNode(4);
problem24 pro=new problem24();
ListNode re=pro.swapPairs(a);
while(re!=null){
System.out.println(re.val);
re=re.next;
}
}
}
2
1
4
3