输入一个链表,反转链表后,输出新链表的表头。
解答:定义一个头结点head,定义一个pre结点为null,定义一个next结点为null。首先让next=head.next;这样保存了head结点下一个结点的信息。然后head.next=pre,让头结点指向了pre结点。然后将指针往后移一位,pre=head,head=next,再继续执行上面操作,最后得到反转的链表。
public class T_15_ReverseList {
public ListNode ReverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode next;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
public class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
}
LeetCode 92 :反转从位置 m 到 n 的链表
- 1 ≤ m ≤ n ≤ 链表长度。
- 输入: 1->2->3->4->5->NULL, m = 2, n = 4
- 输出: 1->4->3->2->5->NULL
public class LC92 {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null) {
return null;
}
ListNode cur = head;
ListNode pre = null;
while (m > 1) {
pre = cur;
cur = cur.next;
m--;
n--;
}
ListNode con = pre;
ListNode tail = cur;
ListNode next;
while (n > 0) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
n--;
}
if (con != null) {
con.next = pre;
} else {
head = pre;
}
tail.next = cur;
return head;
}
}