Reverse a singly linked list.
题意:反转链表
方法一:遍历
思路:使用辅助节点dummy。初始化时dummy..next指向head,并从第二个节点开始遍历,
把遍历过的节点一次插入在dummy节点之后,最后返回dummy.next即可
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
//从第二个节点开始遍历
ListNode curNode = head.next;
//链表尾节点的next设为null
head.next = null;
while (curNode != null) {
//依次插入遍历后的节点
ListNode next = curNode.next;//用来记录curNode的下一个节点的地址
curNode.next = dummy.next;
dummy.next = curNode;
curNode = next;
}
return dummy.next;
}
}
方法二:递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode preNode = head.next;
ListNode n = reverseList(preNode);
head.next = null;
preNode.next = head;
return n;
}
}
第二种方法递归:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;//递归结束条件判断
}
ListNode preNode = head.next;
ListNode n = reverseList(preNode);
head.next = null;
preNode.next = head;//反转指针方向
return n;//返回新链表表头
}
}
Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
为了更好的处理表头和第M个节点的关系,引入dummy节点,此外,还需记录第m-1个节点。从第m个节点开始遍历至第n个节点,已经将遍历过的节点插入在第m-1个节点之后,并保证第m个节点的next指向遍历节点的next,以避免链表断裂。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode curNode = head;
//m的前一个元素
ListNode preNode = dummy;
//m节点
ListNode mNode = new ListNode(0);
ListNode nextNode = null;
for (int i = 1; i <= n; i++) {
//记录第m个节点
if (i == m) mNode = curNode;
//记录m-1个节点
if (i < m ) preNode = preNode.next;
nextNode = curNode.next;
if (i > m && i <= n) {
mNode.next = nextNode;//避免链表断裂
curNode.next = preNode.next;
preNode.next = curNode;
}
curNode = nextNode;
}
return dummy.next;
}
}