链表反转的几种方法

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

题目:给你单链表的头节点 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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是 Java 实现双向链表反转的代码示例: ```java class Node { int data; Node prev; Node next; Node(int data) { this.data = data; this.prev = null; this.next = null; } } class DoublyLinkedList { Node head; DoublyLinkedList() { this.head = null; } void insertAtEnd(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; return; } Node temp = head; while (temp.next != null) { temp = temp.next; } temp.next = newNode; newNode.prev = temp; } void reverse() { if (head == null || head.next == null) { return; } Node current = head; Node temp = null; while (current != null) { temp = current.prev; current.prev = current.next; current.next = temp; current = current.prev; } if (temp != null) { head = temp.prev; } } void display() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } } public class Main { public static void main(String[] args) { DoublyLinkedList dll = new DoublyLinkedList(); dll.insertAtEnd(10); dll.insertAtEnd(20); dll.insertAtEnd(30); dll.insertAtEnd(40); System.out.print("Original list: "); dll.display(); dll.reverse(); System.out.print("Reversed list: "); dll.display(); } } ``` 在上述代码中,我们首先定义了一个 `Node` 类来表示双向链表的节点,每个节点包含一个 `data` 值、一个指向前一个节点的 `prev` 指针和一个指向后一个节点的 `next` 指针。 接下来,我们定义了一个 `DoublyLinkedList` 类来表示双向链表。该类包含一个指向链表头部的 `head` 指针以及一些用于操作链表方法。 其中,`insertAtEnd` 方法用于在链表末尾插入一个新的节点,`reverse` 方法用于反转链表,`display` 方法用于打印链表中所有节点的值。 在 `reverse` 方法中,我们使用了三个指针 `current`、`prev` 和 `temp`,其中 `current` 指向当前节点,`prev` 指向当前节点的前一个节点,`temp` 则用于保存下一个节点的位置。我们不断地遍历链表,将当前节点的 `prev` 和 `next` 指针交换,并将 `current` 指向下一个节点,直到遍历完整个链表。最后,如果链表非空,则将 `head` 指针指向反转后链表的新头部。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值