链表——将单链表从m到n的结点位置翻转

本文介绍了如何在链表中反转指定区间的节点,并通过两种方法实现:原地交换节点和使用辅助空间stack。详细解释了算法逻辑和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:反转链表从m-n位置的结点


For example:
Given1->2->3->4->5->NULL, m = 2 and n = 4,

return1->4->3->2->5->NULL.

从第二到第四的结点被反转了。


其中m和n满足条件:
1 ≤ m ≤ n ≤ length of list.



原地交换结点

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head == null||head.next == null)
            return head;
        if(m == n)
            return head;
        ListNode prefirst=null;//first的前一个结点
        ListNode aftersecond=null;//second的后一个结点
        ListNode first=head;//first引用第m个节点
        ListNode second=null;//secone引用第n个节点
        ListNode p=head;
        for(int i=1;i<=n;i++)
            {
            if(i == m-1)//注意m为1的情况
                {
                prefirst=p;
                first=p.next;
            }
            if(i == n)
                {
                second=p;
                aftersecond=p.next;
            }
            p=p.next;   
        }
        Pair pair=reverse(first,second);
        if(prefirst == null)
            head=pair.head;
        else
            prefirst.next=pair.head;
        pair.rear.next=aftersecond;
        return head;
    }
    //
    public Pair reverse(ListNode head,ListNode rear)
        {
        ListNode pre=head;
        ListNode cur=head.next;
        while(cur!=rear)
            {
            ListNode next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
        cur.next=pre;
        pre=cur;
        rear=head;
        head=pre;
        Pair pair=new Pair(head,rear);
        return pair;
    }
    //定义内部类Pair存储reverse后的head和rear;
  class Pair
      {
      ListNode head;
      ListNode rear;
      public Pair(ListNode head,ListNode rear)
          {
          this.head=head;
          this.rear=rear;
      }
  }
}



仍是逆序,仍考虑到用辅助空间stack.

将m-n的结点依次入栈,并标记与入栈结点相邻的前后两个结点pfirst和psecond

(若m==1,pfirst=null,不管n是否为length of list,对psecond的情况无影响。)


代码如下:

import java.util.*;
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null)
            return null;
        if(m==n)
            return head;
        Stack<ListNode> stack=new Stack();
        //将m-n的结点入栈,将前后相邻的两个结点标记;
        int num=1;
        ListNode pfirst=null;
        ListNode psecond=null;
        ListNode p=head;
        //特殊情况,m==1时,头结点变更;
          if(m==1)
           pfirst=null;
        for(;num<=n;num++)
            {
            //记录pfirst;
             if(num<m)
                {
                if(num==m-1)
                    {
                    pfirst=p;
                }
                p=p.next;  
                }    
            else if(num>=m&&num<=n)
                {
                stack.push(p);
                p=p.next;
            }
        }
        //记录psecond,psecond的一般情况仍适用于n=length of list的特殊情况;
               psecond=p;
        //开始操作链表;
        if(pfirst==null)
            {
            head=stack.pop();
            pfirst=head;
        }
        while(!stack.empty())
            {
            pfirst.next=stack.pop();
            pfirst=pfirst.next;
        }
            pfirst.next=psecond;
        return head;
    }
}

### C语言实现单链表反转 以下是基于提供的引用以及常见实现方式编写的C语言单链表反转代码。此代码采用递归方法来完成链表的反转。 #### 方法一:递归实现 递归是一种常见的解决链表反转的方法,它通过不断调用自身函数直到到达链表末端再逐步返回并调整指针方向。 ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct Node { int data; struct Node* next; } Node; // 创建新节点 Node* create_node(int value) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = value; newNode->next = NULL; return newNode; } // 打印链表 void print_list(Node* head) { while (head != NULL) { printf("%d ", head->data); head = head->next; } printf("\n"); } // 递归反转链表 Node* reverse_recursive(Node* current, Node* previous) { if (current == NULL) { // 如果当前节点为空,则说明已经到了原链表尾部 return previous; // 返回新的头部节点 } Node* next = current->next; // 保存下一个节点 current->next = previous; // 将当前节点指向前面的节点(即反转) return reverse_recursive(next, current); // 继续处理下一个节点 } int main() { // 初始化链表 Node* head = create_node(1); head->next = create_node(2); head->next->next = create_node(3); head->next->next->next = create_node(4); printf("Original list:\n"); print_list(head); // 调用递归反转函数 head = reverse_recursive(head, NULL); printf("Reversed list:\n"); print_list(head); return 0; } ``` 上述代码展示了如何利用递归来反转一个单向链表[^1]。 --- #### 方法二:迭代实现 另一种常用的方式是使用迭代法,这种方法不需要额外的空间开销,并且逻辑相对简单明了。 ```c #include <stdio.h> #include <stdlib.h> // 结构定义同前... // 迭代反转链表 Node* reverse_iterative(Node* head) { Node* prev = NULL; Node* curr = head; Node* next = NULL; while (curr != NULL) { next = curr->next; // 存储下一节点地址 curr->next = prev; // 当前节点指向前一节点 prev = curr; // 前移prev至当前位置 curr = next; // 移动到下一位继续遍历 } return prev; // 新的头结点为最后的prev位置 } int main() { // 链表初始化... printf("Original list:\n"); print_list(head); // 使用迭代方式进行反转 head = reverse_iterative(head); printf("Reversed list via iteration:\n"); print_list(head); return 0; } ``` 这段程序实现了通过循环一步步修改各节点间连接关系从而达到整个列表反序的效果[^2]。 --- #### 方法三:新建链表(头插法) 如果允许创建一个新的链表作为存储空间的话,那么还可以考虑采取头插法来进行操作——每次都将旧链表上的元素摘除下来插入到新建立起来的那个空闲区域最前端处形成最终结果集。 具体实现在参考资料中有提及[^3]: ```c // 头插法构建新链表... ``` 以上三种方案各有优劣,在实际应用当中可根据具体情况选用合适的一种或者多种组合形式加以运用。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值