给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定1->2->3->4
, 你应该返回2->1->4->3
1>暴力遍历
两个一组修改,注意保留前一组的后一个节点指针,用来修改每组的后置指针
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
//先拿到头结点
ListNode res = head.next;
//保存每组的前一个节点
ListNode preNode = null;
while(head.next != null){
if(preNode != null){
preNode.next = head.next;
}
preNode = head;
ListNode nextGroupNode = head.next.next;
head.next.next = head;
head.next = nextGroupNode;
head = nextGroupNode;
if(head == null){
break;
}
}
return res;
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容