题记:只愿大好青春,不负韶华,做自己想做的事!
下面是这一期的第一个算法题:
解决反转链表,可能这是最简单的题,但要去理解它,假设存在链表 1 → 2 → 3 → Ø,我们想要把它改成 Ø ← 1 ← 2 ← 3。在这里我们可以用循环迭代的方式和递归的方式来解决
- 迭代方式:
在遍历列表时,将当前节点的 next 指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。在更改引用之前,还需要另一个指针来存储下一个节点。不要忘记在最后返回新的头引用!
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 循环迭代
def reverseList(self, head: ListNode) -> ListNode:
# 判断是否是节点是否存在,否则直接返回
if head == None:
return head
# 将head 节点赋值新参数
pre = head
# 把当前节点指向下一个节点
curr = head.next
tmp = None
while curr != None:
# 把当前节点值存在临时参数
tmp = curr.next
# 把当前节点的指针指向前一个节点
curr.next = pre
# 替换位置
pre = curr
curr = tmp
# 将原链表的头节点的下一个节点设置为null,再把反转后的头节点赋给head
head.next = None
head = pre
return head
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val) { $this->val = $val; }
* }
*/
class Solution {
/**
* 循环迭代
* @param ListNode $head
* @return ListNode
*/
public function reverseList($head) {
if($head == null) return $head;
$pre = $head; // 取出head节点
$cur = $head->next; // 把当前节点指向下一个节点
$tmp = null;
while($cur != null){
$tmp = $cur->next; //把当前节点值存在临时参数
$cur->next = $pre; // 把当前节点的指针指向前一个节点
$pre = $cur;
$cur = $tmp;
}
// 将原链表的头节点的下一个节点设置为null,再把反转后的头节点赋给head
$head->next = null;
$head = $pre;
return $head;
}
}
- 递归方式:
递归这里的理解可能会比较绕,其关键在于反向工作。不断的递归循环,获取到后面的节点,然后从后面的节点再开始不断替换下一节点数据,来达到反转的形式
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# 判读当前的head节点是否存在或者hedad.next节点是否存在
if not head or head.next == None: return head
# 进行递归操作,直达判读当前的head节点是否存在或者hedad.next节点是否不存在返回
pre = self.reverseList(head.next)
# 将head的下一个节点的下一个节点 替换为当前的head节点
head.next.next = head
# 将head的下一个节点置为None
head.next = None
return pre
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val) { $this->val = $val; }
* }
*/
class Solution {
/**
* 递归
* @param ListNode $head
* @return ListNode
*/
public function reverseList($head) {
if(!$head || $head == null) return $head;
$pre = $this->reverseList($head->next) //把下个节点递归进行判断
$head->next->next = $head //把传进来的当前的节点的下个节点的下个节点赋值为当前节点
$head->next = null;//把当前节点的下个节点值替换为null
return $pre;//返回一个节点数据
}
}
结尾:以上就是用php 和python 解决反转链表的方法和大概思路