力扣206:
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
/**
* 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 ListNode reverseList(ListNode head) {
ListNode prev=null,next=null;
ListNode cur=head;
while(cur!=null){
next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}
return prev;
}
/*递归
public ListNode reverseList1(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode newListNode=reverseList(head.next);
head.next.next=head;
head.next=null;
return newListNode;
}*/
}
力扣92:
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
/**
* 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 ListNode reverseBetween(ListNode head, int left, int right) {
if(head==null) return null;
ListNode listNode=new ListNode(0);
listNode.next=head;
ListNode newNode=listNode;
for(int i=1;i<left;i++){
newNode=newNode.next;
}
ListNode prev=null,next=null;
ListNode cur=newNode.next;
for(int i=left;i<=right;i++){
next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}
newNode.next.next=cur;
newNode.next=prev;
return listNode.next;
}
}