反转链表1
反转链表2
206. 反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null;
ListNode cur=head;
while(cur!=null){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
}
- 反转链表 II
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy=new ListNode(-1);
dummy.next=head;
ListNode p=dummy;
for(int i=1;i<m;i++){
p=p.next;
}
ListNode pre=null;
ListNode cur=p.next;
for(int i=m;i<=n;i++){
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
p.next.next=cur;
p.next=pre;
return dummy.next;
}
}