赞
踩
目录
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]来源:力扣(LeetCode)
- class Solution {
- public ListNode reverseList(ListNode head) {
- if(head==null){
- return null;//避免空指针异常
- }
- ListNode prev=null;
- ListNode cur=head;
- ListNode next=head.next;
- while(cur!=null){
- //翻转
- cur.next=prev;
- //迭代
- prev=cur;
- cur=next;
- if(next!=null)
- next=next.next;
-
- }
- return prev;
- }
- }
- class Solution {
- public ListNode reverseList(ListNode head) {
- ListNode prev = null;
- ListNode curr = head;
- while (curr != null) {
- ListNode next = curr.next;
- curr.next = prev;
- prev = curr;
- curr = next;
- }
- return prev;
- }
- }
- class Solution {
- public ListNode reverseList(ListNode head) {
- ListNode cur=head;
- ListNode newHead=null;
- while(cur!=null){
- ListNode next=cur.next;//借鉴原地反转,避免空指针异常的情况
-
- cur.next=newHead;
- newHead=cur;
- //迭代
- cur=next;
-
- }
- return newHead;
-
-
- }
- }
//这里写下递归
//结束条件:只有一个节点或者没有节点
//处理第一个结点与子链表翻转后的头节点
//返回最终的结点
//1(head)->2->3->null;
z//1(head)->{2<-3(newHead)};
//head->next->next=head;
//head->next=null;
-
- class Solution {
- public ListNode reverseList(ListNode head) {
- if (head == null || head.next == null) {
- return head;
- }
- ListNode newHead = reverseList(head.next);
- head.next.next = head;
- head.next = null;
- return newHead;
- }
- }
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]来源:力扣(LeetCode)
- class Solution {
- public ListNode reverseBetween(ListNode head, int m, int n) {
- ListNode dummy = new ListNode(0);
- dummy.next = head;
- ListNode pre = dummy;
- for(int i = 1; i < m; i++){
- pre = pre.next;
- }
- head = pre.next;
- for(int i = m; i < n; i++){
- ListNode nex = head.next;
- head.next = nex.next;
- nex.next = pre.next;
- pre.next = nex;
- }
- return dummy.next;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。