给你一个链表,请你两两交换相邻节点,你需要真正交换节点本身,而不是修改节点的值。
两两交换示例:
链表 :1->2->3->4
交换后 :2->1->4->3
链表 :1->2->3
交换后: 2->1->3
数据范围:链表长度满足 , 链表上的值满足
public ListNode swapLinkedPair (ListNode head) { if (head.next == null) return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy, p = head, q = head.next; // 穿针引线 while (q != null) { // 交换操作 p.next = q.next; q.next = p; pre.next = q; // 移动操作 pre = p; p = p.next; q = p != null ? p.next : null; } return dummy.next; }
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode swapLinkedPair (ListNode head) { // 不足两个节点直接返回 if(head == null || head.next == null){ return head; } ListNode next = head.next.next; // 把两个节点之后的链表缓存一下 head.next.next = null; // 断链 head = reverseList(head); // 反转当前仅有两个节点的链表 head.next.next = swapLinkedPair(next); // 这两个节点的链表反转之后连接上后续链表反转后的结果 return head; } private ListNode reverseList(ListNode head) { ListNode prev = null; ListNode cur = head; while(cur != null){ ListNode next = cur.next; cur.next = prev; prev = cur; cur = next; } return prev; } }
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ ListNode* swapLinkedPair(ListNode* head) { // write code here ListNode* node = new ListNode(-1); node->next = head; ListNode* cur = node; // 以 1 2 3 4 为例 // 首先cur 指向的是 -1; while(cur->next && cur->next->next) { // tmp 指向 1 ListNode* temp = cur->next; // cur 的下一个指向的 2 cur->next = temp->next; // cur 指向2 cur = cur->next; // tmp 本来指向的是 2 现在转为 指向 2的下一个 3 temp->next = cur->next; // cur是2 原来指向的是3 现在指向 1 cur->next = temp; // cur 等于1 完成一轮转换 可以画个图 很清晰 cur = cur->next; } return node->next; } };
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head ListNode类 # @return ListNode类 # class Solution: def swapLinkedPair(self , head: ListNode) -> ListNode: # write code here new_head = ListNode(0) new_head.next = head node = new_head while node.next is not None: if node.next.next is None: break node_one = node.next node_two = node.next.next node_three = node.next.next.next node_one.next = node_three node_two.next = node_one node.next = node_two node = node_one return new_head.next
public class Solution { public ListNode swapLinkedPair (ListNode head) { // write code here ListNode pre = new ListNode(0); pre.next = head; ListNode ptr = pre; while(ptr.next!=null){ if(ptr.next.next == null){ break; } ListNode a = ptr.next; ListNode b = ptr.next.next; ListNode c = ptr.next.next.next; ptr.next = b; b.next = a; a.next = c; ptr = a; } return pre.next; } }
/** * #[derive(PartialEq, Eq, Debug, Clone)] * pub struct ListNode { * pub val: i32, * pub next: Option<Box<ListNode>> * } * * impl ListNode { * #[inline] * fn new(val: i32) -> Self { * ListNode { * val: val, * next: None, * } * } * } */ struct Solution{ } impl Solution { fn new() -> Self { Solution{} } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ pub fn swapLinkedPair(&self, head: Option<Box<ListNode>>) -> Option<Box<ListNode>> { // write code here let mut dummy_head = Some(Box::new(ListNode::new(233))); dummy_head.as_mut()?.next = head; // println!("{}", dummy_head.as_mut()?.val); let mut p = &mut dummy_head; while p.is_some() && p.as_ref()?.next.is_some() && p.as_ref()?.next.as_ref()?.next.is_some() { let mut a = p.as_mut()?.next.take(); let mut b = a.as_mut()?.next.take(); let mut c = b.as_mut()?.next.take(); p.as_mut()?.next = b; p = &mut p.as_mut()?.next; p.as_mut()?.next = a; p = &mut p.as_mut()?.next; p.as_mut()?.next = c; } dummy_head?.next } }
简单粗暴双指针
import java.util.*; public class Solution { public ListNode swapLinkedPair (ListNode head) { if(head == null || head.next == null) return head; ListNode h = new ListNode(0); h.next = head; ListNode pre = h; ListNode fast = h.next.next; ListNode slow = h.next; while(fast != null) { slow.next = fast.next; pre.next = fast; fast.next = slow; pre = slow; slow = slow.next; if(slow == null) break; fast = slow.next; } return h.next; } }
struct ListNode* swapLinkedPair(struct ListNode* head ) { // write code here struct ListNode* left = head; struct ListNode* right = head->next; struct ListNode* temp = NULL; if ((head == NULL) || (head->next == NULL)) return head; left->next = right->next; right->next = left; head = right; while ((left->next != NULL) && (left->next->next != NULL)) { temp = left; left = left->next; right = left->next; left->next = right->next; right->next = left; temp->next = right; } return head; }
package main import _"fmt" import . "nc_tools" /* * type ListNode struct{ * Val int * Next *ListNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ func swapLinkedPair( head *ListNode ) *ListNode { arr:=[]*ListNode{} for p:=head;p!=nil;p=p.Next{ arr=append(arr,p) } for i:=0;i<len(arr);i+=2{ if i+1<len(arr){ arr[i],arr[i+1]=arr[i+1],arr[i] } } for i,_:=range arr{ if i+1<len(arr){ arr[i].Next=arr[i+1] }else{ arr[i].Next=nil } } return arr[0] }
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ ListNode* swapLinkedPair(ListNode* head) { // write code here //code base if(head == NULL || head->next == NULL) return head; ListNode* next = head->next; head->next = swapLinkedPair(next->next); next->next = head; return next; } };
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ ListNode* swapLinkedPair(ListNode* head) { // write code here if(head == nullptr || head->next == nullptr) return head; ListNode* dummyHead=new ListNode(-1); dummyHead->next=head; ListNode* tail=dummyHead; while(tail->next&&tail->next->next) { ListNode* num1=tail->next; ListNode* num2=tail->next->next; tail->next=num2; num1->next=num2->next; num2->next=num1; tail=num1; } return dummyHead->next; } };
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode swapLinkedPair (ListNode head) { // write code here ListNode res = new ListNode(-1); res.next = head; // 要交换两个节点的前一个节点 ListNode headPre = res; // 后续没有两个节点不在进行交换 while(head != null && head.next != null){ // 要交换两个节点的其中一个(第二个,head是第一个) ListNode temp = head.next; // 要交换两个节点的后面一个节点 ListNode tempNext = head.next.next; // 开始交换 // 要交换两个节点的前一个节点的后面连接到交换节点的第二个 headPre.next = temp; // 第二个节点后面连第一个 temp.next = head; // 第一个后面连要交换两个节点的后面一个节点 head.next = tempNext; // 移动指针 // 前置节点移动 headPre = head; // 第一个交换节点移动 head = tempNext; } return res.next; } }
ListNode* swapLinkedPair(ListNode* head) { // write code here if(!head)return head; ListNode* res=new ListNode(0),*pre=res,*cur,*nxt; res->next=head; while(pre->next && pre->next->next){ cur=pre->next; nxt=cur->next; ListNode* temp=nxt->next; pre->next=nxt; nxt->next=cur; cur->next=temp; pre=cur; } return res->next; }
public ListNode swapLinkedPair (ListNode head) { if(head.next==null)return head; ListNode node=head.next; while(head!=null){ ListNode p=null; if(head.next.next!=null){ p=head.next.next; } head.next.next=head; if(p==null){ head.next=null; }else{ if(p.next==null){ head.next=p; head=p; break; }else{ head.next=p.next; } } head=p; } return node; }
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode swapLinkedPair(ListNode head) { // write code here if (head == null || head.next == null) { return head; } // 虚拟头节点,方便交换head ListNode virtualHead = new ListNode(-1); virtualHead.next = head; ListNode previous = virtualHead; ListNode cur = head; while (cur != null && cur.next != null) { swap(previous, cur); previous = cur; cur = cur.next; } return virtualHead.next; } private void swap(ListNode previous, ListNode cur) { ListNode next = cur.next; cur.next = next.next; previous.next = next; next.next = cur; } }
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ ListNode* swapLinkedPair(ListNode* head) { // write code here typedef ListNode* List; if(!head || !head->next) return head; if(!head->next->next){ List loc = nullptr; loc = head->next; head->next = nullptr; loc->next = head; return loc; } queue<List>ans; List p = head; List newhead = (List)malloc(sizeof(ListNode)); List rear = newhead; //节点全部摘出来 int count = 0; while(p){ count++; ans.push(p); p = p->next; } while(!ans.empty()){ List first = ans.front(); List second = nullptr; ans.pop(); if(!ans.empty()){ second = ans.front(); ans.pop(); } if(first && second){ rear->next = second; second->next = first; first->next = nullptr; } else{ first->next = nullptr; rear->next = first; } rear = first; } return newhead->next; } };
递归求解即可
这里要注意自身交换和进行递归的顺序
如果先交换自身,再递归的话,代码写起来会比较麻烦
如果先递归再交换自身的话,代码写起来就轻松多了
import java.util.*; public class Solution { public ListNode swapLinkedPair (ListNode head) { if (head==null || head.next==null) return head; head.next.next=swapLinkedPair(head.next.next); ListNode newHead = head.next; head.next=newHead.next; newHead.next=head; return newHead; } }
def swapLinkedPair(self, head: ListNode) -> ListNode: # create dummy because head may be moved dummy = ListNode(-1) dummy.next = head prev, curr = dummy, head while curr and curr.next: # save curr_next_next = curr.next.next # reverse prev.next = curr.next curr.next.next = curr curr.next = curr_next_next # move forward prev = curr curr = curr.next return dummy.next