参考自:《剑指Offer——名企面试官精讲典型编程题》
题目:反转链表
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
主要思路:为了反转链表,需要调整链表中每个结点的下一个结点为它的前一个结点。因此,需要3个指针,一个指向前个结点,一个指向当前结点,一个指向下个结点。反转过程:先保存当前结点的下个节点,然后将当前结点的next改为它的前个结点,最后更新指针状态,将前个结点指针和当前结点指针后移一步。
例如:5->4->3->2->1
当前结点指针指向3时:
反转前:previous:5<-4 current:3->2->1 next:2->1
反转后:previous:5<-4<-3(相当于3.next = 4) current:2->1 (更新指针状态)
关键点:当前结点的前后结点互换,保存前后结点
时间复杂度:O(n)
public class ReverseLinkedList {
public static void main(String[] args) {
int[] data = {5, 4, 3, 2, 1};
ListNode head = generateDataByArray(data);
ListNode result = reverseNode(head);
StringBuilder stringBuilder = new StringBuilder();
while (result != null) {
stringBuilder.append(result.val);
result = result.next;
if (result != null) {
stringBuilder.append("->");
}
}
// 1->2->3->4->5
System.out.println(stringBuilder.toString());
}
private static ListNode reverseNode(ListNode head) {
ListNode current = head;
ListNode previous = null;
ListNode next;
while (current != null) {
//保存下一节点
next = current.next;
//相当于添加当前节点在反转链表的表头
//反转前:previous:5<-4 current:3->2->1 next:2->1
//反转后:previous:5<-4<-3(相当于3.next = 4) current:2->1
current.next = previous;
previous = current;
current = next;
}
return previous;
}
private static ListNode generateDataByArray(int[] data) {
ListNode head = new ListNode(data[0]);
ListNode currentNode = head;
for (int i = 1; i < data.length; i++) {
ListNode next = new ListNode(data[i]);
currentNode.next = next;
currentNode = next;
}
return head;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}