OCI 面试经验分享:链表节点反转 | 面试代面, OA代做, 面试辅导
OCI 面试经验分享:链表节点反转 | 面试代面, OA代做, 面试辅导
在这次OCI的面试中,面试官给出了一道关于链表节点反转的题目,要求考生实现一个算法来反转链表中每两个相邻的节点。这道题目考察了考生对链表的基本操作以及对指针操作的熟练程度。在有限的时间内写出正确且高效的代码,对考生的编码能力和算法理解是一个很大的考验。
如果你想在这样的面试中取得好成绩,我们的代面服务能够帮助你深入理解算法,提升编码能力,并在面试中自信地展示你的技能。
想要了解更多或获取我们的服务,欢迎添加微信 leetcode-king。
题目:反转链表中的每两个相邻节点
Problem Description:
Write a function to reverse every two adjacent nodes in a linked list. You should not modify the values in the list's nodes, only the nodes themselves may be changed.
Example:
Given a linked list: 1->2->3->4->5
, the function should return 2->1->4->3->5
.
Code:
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
public ListNode reverseEvery2Nodes(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
ListNode cur = head;
while (cur != null && cur.next != null) {
ListNode nextPair = cur.next.next;
ListNode second = cur.next;
// Reverse the pair
second.next = cur;
cur.next = nextPair;
prev.next = second;
// Update pointers
prev = cur;
cur = nextPair;
}
return dummy.next;
}
public static void main(String[] args) {
Solution solution = new Solution();
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
ListNode result = solution.reverseEvery2Nodes(head);
while (result != null) {
System.out.print(result.val + " ");
result = result.next;
}
}
}