• 嵌入式&C++转java 刷题day2


    还是转java了 用java刷题的感觉就是非常的轻松愉快 只能说java火不是没有道理的

    707. 设计链表

    1. class MyLinkedList {
    2. LinkedList prehead;
    3. class LinkedList{
    4. int val;
    5. LinkedList next;
    6. LinkedList(){
    7. }
    8. LinkedList(int val){
    9. this.val=val;
    10. }
    11. }
    12. public MyLinkedList() {
    13. prehead= new LinkedList();
    14. }
    15. public int get(int index) {
    16. LinkedList cur= prehead.next;
    17. int count=0;
    18. while(cur !=null){
    19. if(count==index){
    20. return cur.val;
    21. }
    22. cur=cur.next;
    23. count++;
    24. }
    25. return -1;
    26. }
    27. public void addAtHead(int val) {
    28. LinkedList node = new LinkedList(val);
    29. node.next=prehead.next;
    30. prehead.next=node;
    31. }
    32. public void addAtTail(int val) {
    33. LinkedList cur= prehead;
    34. LinkedList node = new LinkedList(val);
    35. while(cur.next!=null){
    36. cur=cur.next;
    37. }
    38. cur.next=node;
    39. }
    40. public void addAtIndex(int index, int val) {
    41. LinkedList pre= prehead;
    42. LinkedList cur=prehead.next;
    43. LinkedList node = new LinkedList(val);
    44. int count=0;
    45. while(cur!=null){
    46. if(count==index){
    47. pre.next=node;
    48. node.next=cur;
    49. return;
    50. }
    51. cur=cur.next;
    52. pre=pre.next;
    53. count++;
    54. }
    55. if(index==count){
    56. addAtTail(val);
    57. }
    58. }
    59. public void deleteAtIndex(int index) {
    60. int count=0;
    61. LinkedList pre= prehead;
    62. while(pre.next!=null){
    63. if(count==index){
    64. pre.next=pre.next.next;
    65. return;
    66. }
    67. pre=pre.next;
    68. count++;
    69. }
    70. }
    71. }

    设计链表 用C++写非常困难  但是用java的话就简单太多了 很多细节都不用处理  就是注意下面几个点:1 this.val=val 这是java中的叫隐藏的this调用吧 2 你这个prehead也就是函数中的局部变量 你要是说想全局去显示的话,你需要把它写到属性的位置。

    class Solution {

        public ListNode reverseList(ListNode head) {

            ListNode pre=null;

            ListNode cur=head;

            while(cur!=null){

                ListNode tmp= cur.next;

                cur.next=pre;

                pre=cur;

                cur=tmp;

            }

            return pre;

        }

    }

    这个还是说要想到 不是说一下子操作两个结点 而是一个结点一个结点的操作 且最后是Null 所以不需要新加一个头结点。

     

  • 相关阅读:
    总结SQL中add constraint的用法
    java保留两位小数4种方法
    vue+mysql实现前端对接数据库
    信息技术服务连续性策略
    R语言数学建模(二)—— tidymodels
    六、TCP实现聊天
    Linux/Ubuntu/Debian 常用用户管理命令
    价值9890元的600集Python教程,在此透露给大家!速度来拿哇
    响应式基础
    打印lua输出日志
  • 原文地址:https://blog.csdn.net/feifeikon/article/details/134060363