# Python3、Java 实战LeetCode高频面试之单链表反转

### 单链表反转

输入: 1->2->3->4->5->NULL



### 方法一：迭代法

#### 代码实现

Python3 实现

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# pre 就是那个空链表
# 不断将当前链表移动到空链表上
while cur:
next_node = cur.next
cur.next = pre
pre = cur
cur = next_node
return pre


Java 实现

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
}
ListNode pre = null;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}


### 方法二：递归法

#### 代码实现

Python3 实现

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# 防止出现环
return node


Java 实现

/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
}
return node;
}
}


### 总结

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

与你一起学算法

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

11-21 2568
03-21 2384
08-23 8297
06-03 1万+
06-27 4393
04-04 4093
08-31 3619
12-30 1359
08-01 2313
05-14 3831
02-12 1586
05-21 2009
03-10 521
09-19 2021
06-10 2287