一、反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
二、遍历与递归解法
package cn.edu.neu.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* Definition for singly-linked list.
*/
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
/**
* @author 32098
*
* 反转链表
*
* 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
*/
public class ReverseLinkedList {
public static ListNode reverseList(ListNode head) {
ListNode prevNode = null;
ListNode curNode = head;
// 反转列表反转指针即可
while (curNode!=null){
// 获取curNode的next节点
ListNode next = curNode.next;
// 修改curNode的next节点为prevNode
curNode.next = prevNode;
// prevNode设置为curNode
prevNode = curNode;
// 新的curNode
curNode = next;
}
return prevNode;
// ListNode ans = null;
// for (ListNode x = head; x != null; x = x.next) {
// ans = new ListNode(x.val, ans);
// }
// return ans;
}
public static ListNode reverseListRecursive(ListNode head) {
// 1. 递归终止条件
if (head == null || head.next == null) {
return head;
}
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
public static void printLinkedList(ListNode head){
List<Integer> vals = new ArrayList<>();
ListNode curNode = head;
while (curNode!=null){
vals.add(curNode.val);
curNode = curNode.next;
}
System.out.println(vals);
}
public static void main(String[] args) {
ListNode curNode = new ListNode(0);
ListNode finalNode = curNode;
for(int i=1; i<6; i++){
curNode.next = new ListNode(i);
curNode = curNode.next;
}
printLinkedList(finalNode);
// printLinkedList(reverseList(finalNode));
printLinkedList(reverseListRecursive(finalNode));
}
}