NO.4 剑指Offer
2021/8/6 6:09:35
本文主要是介绍NO.4 剑指Offer,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
剑指Offer第4天刷题
今天开始复习链表:
翻转链表
需要保留一个节点的前驱和后继,用cur来遍历节点,head就是它的前驱,curNext是它的后继
public class Solution { public ListNode ReverseList(ListNode head) { if(head == null) return null; ListNode cur = head; ListNode curNext = cur.next; cur.next = null; cur = curNext; while(cur != null){ curNext = cur.next; cur.next = head; head = cur; cur = curNext; } return head; } }
合并两个排序的链表
定义一个傀儡节点,让两个链表依次比较,头最小的作为它的后继,遍历两个链表,最后一个链表遍历完成之后,将另一个链表剩下的部分直接放过来最后返回傀儡节点的下一个节点就是新链表的头结点。
public class Solution { public ListNode Merge(ListNode list1,ListNode list2) { ListNode newHead = new ListNode(-1); ListNode cur = newHead; while(list1 != null && list2 != null){ if(list1.val <= list2.val){ cur.next = list1; list1 = list1.next; }else{ cur.next = list2; list2 = list2.next; } cur = cur.next; } if(list1 != null) cur.next = list1; if(list2 != null) cur.next = list2; return newHead.next; } }
删除链表中重复的结点
定义一个傀儡节点,让链表从头结点(cur)就开始与后一个(cur.next)比较,保留它的前驱prev,如果相同,就让cur一直往后走,直到不相同为止,然后将新的cur作为prev的后继,最后将链表的最后一个节点的next设置为null,防止有最后一个节点也是重复的。
public class Solution { public ListNode deleteDuplication(ListNode pHead) { ListNode newHead = new ListNode(-1); ListNode prev = newHead; ListNode cur = pHead; while(cur != null){ if(cur.next != null && cur.val == cur.next.val){ while(cur.next != null && cur.val == cur.next.val){ cur = cur.next; } cur = cur.next; }else{ prev.next = cur; prev = prev.next; cur = cur.next; } } prev.next = null; return newHead.next; } }
这篇关于NO.4 剑指Offer的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)