链表反转的几种方法

在链表的考查中,链表的反转是比较常见的,在此介绍几种常用的方法

题目:给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

1.迭代法(双指针)

假设链表为 1→2→3→∅,把它改成 ∅←1←2←3。

在遍历链表时,将当前节点的 next 指针改为指向前一个节点。但是由于节点没有引用其前一个节点,因此必须要准备一个指针事先存储其前一个节点。在更改引用之前,还需要存储后一个节点。最后返回新的头引用。

  struct ListNode {
      int val;
      struct ListNode *next;
  };
 
struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode*prev=NULL;
    struct ListNode*curr=head;
    while(curr)
    {
        struct ListNode*next=curr->next;
        curr->next=prev;
        prev=curr;
        curr=next;
    }
    return prev;
}

这里也提供python的写法,更加简便

class ListNode:
     def __init__(self, val=0, next=None):
         self.val = val
         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        cur, pre = head, None
        while cur:
            cur.next, pre, cur = pre, cur, cur.next
        return pre

 

 2.递归法

用递归法相比于迭代法,重要的是如何处理已经被反转的部分,即递归到第一个节点n1时,n1​ 的下一个节点必须指向 ∅,否则会产生环形链表


  struct ListNode {
      int val;
      struct ListNode *next;
  };
 
struct ListNode* reverseList(struct ListNode* head) {
    if (head == NULL || head->next == NULL) {
        return head;
    }
    struct ListNode* newHead = reverseList(head->next);
    head->next->next = head;
    head->next = NULL;
    return newHead;
}

提供来自官网的python写法

class ListNode:
     def __init__(self, val=0, next=None):
         self.val = val
         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        def recur(cur, pre):
            if not cur: return pre     # 终止条件
            res = recur(cur.next, cur) # 递归后继节点
            cur.next = pre             # 修改节点引用指向
            return res                 # 返回反转链表的头节点     
        return recur(head, None)       # 调用递归并返回

 3.头插法

头插法先将前面的节点断开,进行后面数据插入

typedef struct List{
    int val;
    struct List *next;
}List;
List*Headback(List*phead)
{
	List*p=phead->next;
	phead->next=NULL;
	List*q;
	while(p!=NULL){
		q=p->next;
		p->next=phead->next;
		phead->next=p;
		p=q;
	}
	return phead;
}
### 链表反转算法的实现方法 链表反转一个经典的算法问题,在不同的编程语言中有多种实现方式。以下是几种常见的方式及其具体实现。 #### 使用迭代方法(以C为例) 在C语言中,可以使用三个指针变量`pre`、`cur`和`temp`来完成链表反转操作。初始时,`pre`设为`NULL`,表示新的链表头部;`cur`指向原始链表的头节点。每次循环中,先保存`cur->next`到临时变量`temp`,然后修改`cur->next`使其指向`pre`,最后更新`pre`和`cur`的位置以便处理下一个节点[^4]。 ```c struct ListNode* reverseList(struct ListNode* head) { struct ListNode* pre = NULL; struct ListNode* cur = head; while (cur != NULL) { struct ListNode* temp = cur->next; cur->next = pre; pre = cur; cur = temp; } return pre; } ``` #### 使用递归的方法(以Python为例) 递归方法的核心思想是从链表的尾部开始逐步构建反转后的链表。对于每个节点,将其后续部分视为已经反转好的子链表,然后调整当前节点与其后续节点之间的关系。 ```python def reverse_list(head): if not head or not head.next: return head reversed_head = reverse_list(head.next) head.next.next = head head.next = None return reversed_head ``` #### C#中的链表反转实现 在C#中,同样可以通过遍历链表并逐个更改节点间的链接方向来实现链表反转。这种方法类似于C语言中的迭代法[^3]。 ```csharp public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } } public static ListNode ReverseList(ListNode head) { ListNode prev = null; ListNode current = head; while(current != null){ ListNode nextTemp = current.next; current.next = prev; prev = current; current = nextTemp; } return prev; } ``` #### 双向链表反转 对于双向链表而言,除了需要交换前后两个方向上的指针外,还需要特别注意首尾节点的变化以及可能存在的边界条件处理[^5]。 ```java public void reverse() { Node<T> temp = null; Node<T> current = head; while (current != null) { temp = current.prev; current.prev = current.next; current.next = temp; current = current.prev; } if(temp != null ){ head = temp.prev; } } ``` 以上就是关于单向与双向链表反转的一些基本思路及其实现代码示例。每种语言都有自己的特点,因此具体的编码风格可能会有所差异,但核心逻辑保持一致。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值