c语言sscanf函数的用法是什么
247
2022-12-01
206. Reverse Linked List
Reverse a singly linked list.
click to show more hints.
Hint: A linked list can be reversed either iteratively or recursively. Could you implement both?
iterative 解法:
总结就是得到下一个节点,更改当前节点指向,将指针往下移动,直到过完整个linkedlist.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode reverseList(ListNode head) { ListNode prev = null; ListNode cur = head; while(cur!=null){ ListNode next = cur.next; cur.next = prev; prev = cur; cur = next; } return prev; }}
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next==null) return head; // 1->2->3->4->null ListNode nextNode = head.next; // 2->3->4->null ListNode reversed = reverseList(nextNode); //4->3->2->null nextNode.next = head; //4->3->2->1 head.next = null; //4->3->2->1->null return reversed; }}
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode reverseList(ListNode head) { ListNode rev = null; ListNode temp1 = head; while(temp1 != null) { if (rev == null) { rev = new ListNode(temp1.val); } else { ListNode tnew = new ListNode(temp1.val); tnew.next = rev; rev = tnew; } temp1 = temp1.next; } return rev; }}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~