//交换单链表的相邻节点
public Node swapPairs(Node head) {
if(head == null||head.next==null){
return head;
}
Node cur = head;
Node prev = cur; // 连接每对节点
if(cur.next != null){
head = cur.next;
}
while(cur != null && cur.next != null){
prev.next = cur.next;
Node next = cur.next.next; // next用来保存下一对节点的开始节点
cur.next.next = cur;
cur.next = next;
prev = cur; // prev指向每一对反转之后节点的第二个节点
cur = next; // cur指向每一对节点的第一个节点
}
return head;
}
链表-交换单链表的相邻节点
猜你喜欢
转载自blog.csdn.net/weixin_42146769/article/details/88524790
今日推荐
周排行