//给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
//
// 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
//
//
//
// 示例:
//
// 给定 1->2->3->4, 你应该返回 2->1->4->3.
//
// Related Topics 链表
// 👍 676 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode root = new ListNode(-1);
root.next = head;
ListNode pre = root;
if(head == null||head.next==null){
return head;
}
ListNode p = head;
ListNode q = head.next;
while (p != null && q != null) {
pre.next = q;
p.next = q.next;
q.next = p;
pre = pre.next.next;
if( pre == null||pre.next==null){
break;
}else{
p = pre.next;
q = pre.next.next;
}
}
return root.next;
}
}
//leetcode submit region end(Prohibit modification and deletion)
leetcode-24两两交换链表中的节点
最新推荐文章于 2024-04-28 16:03:45 发布