重点: 构造虚拟节点,每两个一组进行循环处理
public ListNode swapPairs(ListNode head) {
// 虚拟节点
ListNode dumyhead = new ListNode(0);
dumyhead.next = head;
//当前节点
ListNode cur = dumyhead;
while (cur.next != null && cur.next.next != null) {
//取出临时节点
ListNode first= cur.next;
ListNode second = cur.next.next;
ListNode third = cur.next.next.next;
//替换
cur.next = second;
second.next = first;
first.next = third;
//更新指针(当前第二个位置是first)
cur = first;
}
return dumyhead.next;
}
public ListNode swapPairs(ListNode head) {
// base case 退出提交
if(head == null || head.next == null) return head;
// 获取当前节点的下一个节点
ListNode next = head.next;
// 进行递归
ListNode newNode = swapPairs(next.next);
// 这里进行交换
next.next = head;
head.next = newNode;
return next;
}
原文地址:https://blog.csdn.net/xueluoyouying/article/details/135991136
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_64967.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!