剑指Offer之Java算法习题精讲链表专题篇

网友投稿 270 2022-08-19


剑指Offer之Java算法习题精讲链表专题篇

题目一

解法

/**

* Definition for singly-linked list.

* public class ListNode {

* int val;

* ListNode next;

* ListNode() {}

* ListNode(int val) { this.val = val; }

* ListNode(int val, ListNode next) { this.val = val; this.next = next; }

* }

*/

class Solution {

public int getDecimalValue(ListNode head) {

int[] arr = new int[31];

int index = 0;

int ans = 0;

while(head!=null){

arr[index] = head.val;

index++;

head = head.next;

}

for(int i = 0;i

if(arr[i]==1){

ans+=(1<<(index-1-i));

}

}

return ans;

}

}

题目二

解法

/**

* Definition for singly-linked list.

* public class ListNode {

* int val;

* ListNode next;

* ListNode(int x) { val = x; }

* }

*/

class Solution {

public int[] reversePrint(ListNode head) {

int index = 0;

ListNode h = head;

while(head!=null){

head = head.next;

http:// index++;

}

int[] arr = new int[index];

while(h!=null){

arr[index-1] = h.val;

index--;

h = h.next;

}

return arr;

}

}

题目三

解法

/**

* Definition for singly-linked list.

* public class ListNode {

* int val;

* ListNode next;

* ListNode(int x) { val = x; }

* }

*/

class Solution {

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

ListNode node = new ListNode(-1);

ListNode ans = node;

while(l1!=null&&l2!=null){

if(l1.val<=l2.val){

node.next = l1;

l1 = l1.next;

}else{

node.next = l2;

l2 = l2.next;

}

node = node.next;

}

if(l1!=null){

node.next = l1;

}

if(l2!=null){

mvBfi node.next = l2;

}

return ans.next;

}

}

if(arr[i]==1){

ans+=(1<<(index-1-i));

}

}

return ans;

}

}

题目二

解法

/**

* Definition for singly-linked list.

* public class ListNode {

* int val;

* ListNode next;

* ListNode(int x) { val = x; }

* }

*/

class Solution {

public int[] reversePrint(ListNode head) {

int index = 0;

ListNode h = head;

while(head!=null){

head = head.next;

http:// index++;

}

int[] arr = new int[index];

while(h!=null){

arr[index-1] = h.val;

index--;

h = h.next;

}

return arr;

}

}

题目三

解法

/**

* Definition for singly-linked list.

* public class ListNode {

* int val;

* ListNode next;

* ListNode(int x) { val = x; }

* }

*/

class Solution {

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

ListNode node = new ListNode(-1);

ListNode ans = node;

while(l1!=null&&l2!=null){

if(l1.val<=l2.val){

node.next = l1;

l1 = l1.next;

}else{

node.next = l2;

l2 = l2.next;

}

node = node.next;

}

if(l1!=null){

node.next = l1;

}

if(l2!=null){

mvBfi node.next = l2;

}

return ans.next;

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:使用Spring Boot 2.x构建Web服务的详细代码
下一篇:剑指Offer之Java算法习题精讲二叉树与斐波那契函数
相关文章

 发表评论

暂时没有评论,来抢沙发吧~