反转链表
牛客题霸NC78
难度:Easy
题目描述:
输入一个链表,反转链表后,输出新链表的表头。
示例:
| 12
 3
 4
 
 | 输入:{1, 2, 3}
 输出:
 {3, 2, 1}
 
 | 
解决方法:
1.通过栈+尾插法实现
可以将所有节点入栈,然后逐个出栈,插入到链表尾部。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 
 | import java.util.*;
 
 
 
 
 
 
 
 
 public class Solution {
 public ListNode ReverseList(ListNode head) {
 
 Stack<ListNode> stack = new Stack<>();
 while(head != null){
 stack.push(head);
 head = head.next;
 }
 
 ListNode newHead = null;
 ListNode tail = null;
 while(!stack.isEmpty()){
 ListNode node = stack.pop();
 node.next = null;
 if(newHead == null){
 newHead = node;
 tail = node;
 }
 else{
 tail.next = node;
 tail = node;
 }
 
 }
 
 return newHead;
 }
 }
 
 | 
2.头插法
我们要将链表逆序,可以遍历原链表,对每个节点采用头插法插入到新链表中即可实现反转。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 
 | 
 
 
 
 
 
 
 
 public class Solution {
 public ListNode ReverseList(ListNode head) {
 
 ListNode newHead = null;
 
 while(head != null){
 ListNode nextNode = head.next;
 head.next = newHead;
 newHead = head;
 head = nextNode;
 }
 
 return newHead;
 
 }
 }
 
 | 
3.通过递归实现
递归也可以实现链表反转,但是效率比较低。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 
 | 
 
 
 
 
 
 
 
 public class Solution {
 public ListNode ReverseList(ListNode head) {
 
 if(head == null || head.next == null){
 return head;
 }
 
 ListNode newHead = ReverseList(head.next);
 
 head.next.next = head;
 head.next = null;
 
 return newHead;
 
 }
 }
 
 | 
原文作者: NTJD
原文链接: http://yoursite.com/2020/11/05/牛客题霸反转链表题解/
版权声明: 转载请注明出处(必须保留作者署名及链接)