admin管理员组文章数量:1028560
链表系列一>两两交换链表中的结点
题目:
链接: link
解析:
代码:
代码语言:javascript代码运行次数:0运行复制/**
* 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) {
if(head == null || head.next == null) return head;
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode prev = newHead;
ListNode cur = prev.next, next = cur.next,Nnext = next.next;
while(cur != null && next != null){
//交换节点
prev.next = next;
next.next = cur;
cur.next = Nnext;
//交换之后继续往后走
prev = cur;
cur = Nnext;
if(cur != null)
next = cur.next;
if(next != null)
Nnext = next.next;
}
return newHead.next;
}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-04-26,如有侵权请联系 cloudcommunity@tencent 删除return链表intnullpublic链表系列一>两两交换链表中的结点
题目:
链接: link
解析:
代码:
代码语言:javascript代码运行次数:0运行复制/**
* 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) {
if(head == null || head.next == null) return head;
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode prev = newHead;
ListNode cur = prev.next, next = cur.next,Nnext = next.next;
while(cur != null && next != null){
//交换节点
prev.next = next;
next.next = cur;
cur.next = Nnext;
//交换之后继续往后走
prev = cur;
cur = Nnext;
if(cur != null)
next = cur.next;
if(next != null)
Nnext = next.next;
}
return newHead.next;
}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-04-26,如有侵权请联系 cloudcommunity@tencent 删除return链表intnullpublic本文标签: 链表系列一>两两交换链表中的结点
版权声明:本文标题:链表系列一>两两交换链表中的结点 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/jiaocheng/1747502081a2169363.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论