L2-022 重排链表 (25分)

本文详细介绍了一种链表重排算法的实现过程,通过扫描链表并将元素按特定顺序重新连接,达到重排目的。文章包含完整的C++代码示例,展示了如何读取链表节点信息,并使用两遍扫描策略完成链表的重排。

L2-022 重排链表 (25分)

AC代码

#include <iostream>
#include <cstdio>
using namespace std;
struct node{
    int cur, value, nxt;
}nodes[100010], h[100010], ret[100010], ans[100010];
int main(){
    int ori, n, pos = 0, index = 0, cnt = 0;
    scanf("%d%d", &ori, &n);
    for (int i = 0; i < n; i++){
        scanf("%d%d%d", &nodes[i].cur, &nodes[i].value, &nodes[i].nxt);
        h[nodes[i].cur] = nodes[i];
    }
    while (true){
        ret[pos++] = h[ori];
        cnt++;
        if (h[ori].nxt == -1) break;
        ori = h[ori].nxt;
    }
    for (int i = 0; i < cnt/2; i++){
        ans[index++] = ret[cnt-i-1];
        ans[index++] = ret[i];
    }
    if (cnt%2) ans[index++] = ret[cnt/2];
    for (int i = 0; i < index-1; i++)
        printf("%05d %d %05d\n", ans[i].cur, ans[i].value, ans[i+1].cur);
    printf("%05d %d -1", ans[index-1].cur, ans[index-1].value);
    return 0;
}
### L2-022 重排链表 Java 实现 为了实现给定的链表重新排列,可以采用双指针法来找到中间节点并反转后半部链表。之后再将两个子链表交替合并。 #### 定义链表结构 首先定义单向链表的数据结构: ```java class ListNode { int val; ListNode next; public ListNode(int x) { this.val = x; this.next = null; } } ``` #### 找到中间结点 通过快慢指针的方法寻找链表的中间位置,并将其为两部[^1]。 ```java private static ListNode findMiddleNode(ListNode head) { if (head == null || head.next == null) return head; ListNode slow = head, fast = head; while (fast != null && fast.next != null) { System.out.println("pre " + slow.val + " " + fast.val); slow = slow.next; fast = fast.next.next; } return slow; } ``` #### 反转链表 对于割后的右半边链表执行翻转操作以便后续连接时能够按照题目要求顺序相连[^3]。 ```java public static ListNode reverseList(ListNode head) { ListNode prev = null; ListNode curr = head; while (curr != null) { ListNode tempNext = curr.next; curr.next = prev; prev = curr; curr = tempNext; } return prev; } ``` #### 合并链表 最后一步就是把前一半和经过逆转处理过的另一半依次交叉拼接起来形成最终结果。 ```java public void reorderList(ListNode head) { if(head==null||head.next==null){ return ; } // Find the middle of linked list [Problem 876] ListNode mid=findMiddleNode(head); // Reverse the second part of the list [Problem 206] ListNode l1=head,l2=mid.next; mid.next=null; l2=reverseList(l2); // Merge two sorted linked lists [Problem 21] mergeTwoLists(l1,l2); } // Helper function to interweave nodes from both halves. private void mergeTwoLists(ListNode l1,ListNode l2){ while(l1!=null&&l2!=null){ ListNode tmp1=l1.next,tmp2=l2.next; l1.next=l2;l2.next=tmp1; l1=tmp1;l2=tmp2; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值