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 54 55 56
| class ListNode { int val; ListNode next;
ListNode(int val){ this.val=val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class ListNode { int val; ListNode next;
ListNode(int val){ this.val=val; } }
class Test{ public static void main(String[] args){
ListNode Listnode = new ListNode(0); ListNode nextNode; nextNode=Listnode;
for(int i=1;i<10;i++){ ListNode node = new ListNode(i); nextNode.next=node; nextNode=nextNode.next; }
nextNode=Listnode; print(nextNode);
}
static void print(ListNode listNoed){ while(listNoed!=null){ System.out.println("节点:"+listNoed.val); listNoed=listNoed.next; } System.out.println(); }
}
|
ListNode 初始化
编程题当中,当需要用到ListNode的时候需要这样初始化,同时,下面的代码默认ListNode中装的是int,这里的int也可以改为其他,如char,string
- 在节点ListNode定义中,定义为节点为结构变量。
- 节点存储了两个变量:value 和 next。value 是这个节点的值,next 是指向下一节点的指针,当 next 为空指针时,这个节点是链表的最后一个节点。
- 注意注意val只代表当前指针的值,比如p->val表示p指针的指向的值;而p->next表示链表下一个节点,也是一个指针。
- 构造函数包含两个参数 _value 和 _next ,分别用来给节点赋值和指定下一节点
- 也有只有一个参数的构造方法,一般是存值,然后指针会默认指向null,可以应用于哨兵结点等
————————————————
原文链接:https://blog.csdn.net/humor2020/article/details/123683086
ListNode 相关操作逻辑
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
| class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
ListNode node = new ListNode(1);
ListNode node = new ListNode(1); node.next = new ListNode(2); node.next.next = new ListNode(3);
ListNode curr = node; while (curr != null) { System.out.println(curr.val); curr = curr.next; }
ListNode node = new ListNode(1); node.next = new ListNode(2);
ListNode newNode = new ListNode(3); newNode.next = node.next; node.next = newNode;
ListNode node = new ListNode(1); node.next = new ListNode(2);
node.next = node.next.next;
ListNode node = new ListNode(1); node.next = new ListNode(2); node.next.next = new ListNode(3);
ListNode prev = null; ListNode curr = node; while (curr != null) { ListNode next = curr.next; curr.next = prev; prev = curr; curr = next; } node = prev;
|
————————————————
原文链接:https://blog.csdn.net/qq_45450889/article/details/130935675