高频面试题总结之翻转链表

高频面试题总结 —— 翻转链表

翻转链表是面试中常见的题目,这并不是什么难题,因为要实现翻转,所以一般需要有两个ListNode,通过改变这两个ListNode的前后节点及循环移动这两个节点从而实现链表的翻转。

初级翻转链表

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

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
47
48
49
50
51
52
53
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/*
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
/**
* 1.
*
* */
/**非递归实现
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
ListNode dummy = new ListNode(-1);
while (cur != null) {
ListNode temp = cur.next;
cur.next = dummy.next;
dummy.next = cur;
cur = temp;
}
return dummy.next;**/
//递归实现
if (head == null || head.next == null) {
return head;
}
ListNode nextNode = head.next;
head.next = null;
ListNode reverseResourse = reverse(nextNode);
nextNode.next = head;
return reverseResourse;
}
}

翻转部分链表

翻转链表中第m个节点到第n个节点的部分
给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null

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
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: ListNode head is the head of the linked list
* @param m: An integer
* @param n: An integer
* @return: The head of the reversed ListNode
*/
public ListNode reverseBetween(ListNode head, int m, int n) {
// write your code here
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head;
for (int i = 1; i < m; i++) {
pre = pre.next;
cur = cur.next;
}
//与翻转链表的不同是要保持第一个节点不变
for (int i = 0; i < n - m; i++) {
ListNode temp = cur.next;
cur.next = temp.next;
temp.next = pre.next;
pre.next = temp;
}
return dummy.next;
}
}
Compartir Comentarios