Last updated on 2023年9月23日 晚上
25. K 个一组翻转链表(Java实现)
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
|
class Solution { public ListNode reverseKGroup(ListNode head, int k) { Stack<ListNode> st = new Stack(); ListNode resultNode = new ListNode(0); ListNode prev = resultNode;
while(true){ ListNode tempNode = head; int count = 0;
while(tempNode != null && count < k){ st.push(tempNode); tempNode = tempNode.next; count ++; }
if(count < k){ break; }
while(!st.empty()){ prev.next = new ListNode(st.peek().val); st.pop(); prev = prev.next; }
prev.next = tempNode;
head = tempNode; }
return resultNode.next;
} }
|
138. 随机链表的复制(Java实现)
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
| /* // Definition for a Node. class Node { int val; Node next; Node random;
public Node(int val) { this.val = val; this.next = null; this.random = null; } } */
class Solution { public Node copyRandomList(Node head) { //思路:实现链表的深拷贝 //如果head结点等于null,直接返回null if(head == null){ return head; }
//指针指向head Node node = head; //使用map保存原始结点和新的结点 Map<Node, Node> map = new HashMap<>();
//遍历原始结点 while(node != null){ //创建和node.val相同的但是next和random等待初始化的结点 Node tmp = new Node(node.val, null, null); map.put(node, tmp); //更新node指针 node = node.next; }
//node指向head node = head; while(node != null){ map.get(node).next = map.get(node.next); map.get(node).random = map.get(node.random); node = node.next; }
return map.get(head);
} }
|
leetcode-hot-100-20230923
https://thewangyang.github.io/2023/09/23/leetcode-hot-100-20230923/