反转链表
题目
反转一个单链表
输入:1->2->3->4->5->NULL
输出:5->4->3->2->1->NULL
分析
1.利用辅助空间
1.1将链表数据拷贝到动态链表中
1.2动态数组内容反转
1.3读取动态数组中的内容
时间复杂度 O(N)
空间复杂度 O(N)
2.迭代实现
2.1创建两个指针
2.2 两个指针不断往前移,同时改变数据之间的指向关系
注意:用一个tmp指针保存cur.next,否则pre和cur无法正常向后移动。
时间复杂度 O(N)
空间复杂度 O(1)
3.递归实现
比较复杂,出力不讨好,看看就行。
时间复杂度 O(N)
空间复杂度 O(N)
代码
辅助代码
ListNode
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;
}
}
打印工具类
public class UtilListNode {
public static void printNode(ListNode head) {
if (head == null) {
System.out.println("Empty!");
return;
}
StringBuilder sb = new StringBuilder();
while (head != null) {
sb.append(head.val);
if (head.next != null) {
sb.append("-->");
} else {
sb.append("-->NULL");
}
head = head.next;
}
System.out.println(sb.toString());
}
}
利用辅助空间
public class ReverseList {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ArrayList<Integer> arr = new ArrayList<>();
ListNode p = head;
while (p != null) {
arr.add(p.val);
p = p.next;
}
Collections.reverse(arr);
p = head;
for (int i = 0; i < arr.size(); i++) {
p.val = arr.get(i);
p = p.next;
}
return head;
}
public void test() {
ListNode a1 = new ListNode(1);
ListNode a2 = new ListNode(2);
ListNode a3 = new ListNode(3);
ListNode a4 = new ListNode(4);
ListNode a5 = new ListNode(5);
a1.next = a2;
a2.next = a3;
a3.next = a4;
a4.next = a5;
UtilListNode.printNode(a1);
UtilListNode.printNode(reverseList(a1));
}
public static void main(String[] args) {
ReverseList t=new ReverseList();
t.test();
}
}
迭代代码
public class ReverseList {
public ListNode reverseList_2(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
public void test() {
ListNode a1 = new ListNode(1);
ListNode a2 = new ListNode(2);
ListNode a3 = new ListNode(3);
ListNode a4 = new ListNode(4);
ListNode a5 = new ListNode(5);
a1.next = a2;
a2.next = a3;
a3.next = a4;
a4.next = a5;
UtilListNode.printNode(a1);
UtilListNode.printNode(reverseList_2(a1));
}
public static void main(String[] args) {
ReverseList t = new ReverseList();
t.test();
}
}
递归代码
public class ReverseList {
public ListNode reverseList_3(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = reverseList_3(head.next);
head.next.next = head;
head.next = null;
return cur;
}
public void test() {
ListNode a1 = new ListNode(1);
ListNode a2 = new ListNode(2);
ListNode a3 = new ListNode(3);
ListNode a4 = new ListNode(4);
ListNode a5 = new ListNode(5);
a1.next = a2;
a2.next = a3;
a3.next = a4;
a4.next = a5;
UtilListNode.printNode(a1);
UtilListNode.printNode(reverseList_3(a1));
}
public static void main(String[] args) {
ReverseList t = new ReverseList();
t.test();
}
}