实现单链表反转

链表实现以及反转链表

实现

1
2
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
39
40
41
42
43
44
45
46
package com.test.algorithm;

public class SingleListReverse {
static class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}

/**
* temp = b a.next = null prev = a head = b
* temp = c b.next = a prev = b head = c
* temp = d c.next = b prev = c head = d
* temp = null d.next = c prev = d head = null
*
* @param head
* @return
*/
private static ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}

public static void main(String[] args) {
ListNode a = new ListNode(1);
ListNode b = new ListNode(2);
ListNode c = new ListNode(3);
ListNode d = new ListNode(4);
a.next = b;
b.next = c;
c.next = d;

ListNode result = reverseList(a);
System.out.println(result.next.val);
}
}