1. 指定区间反转
头插法
使用虚拟头节点
首先移动到待反转节点的前一个位置
将新节点移动到前边
/**
* 方法2:头插法
* 首先移动到待反转节点的前一个位置
* 将新节点移动到前边
* @param head
* @param left
* @param right
* @return
*/
public static ListNode reverseBetween2(ListNode head, int left, int right) {
// 设置 dummyNode 是这一类问题的一般做法
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
for (int i = 0; i < left - 1; i++) {
pre = pre.next;
}
ListNode cur = pre.next;
for (int i = 0; i < right - left; i++) {
ListNode next = cur.next;
cur.next = next.next;
next.next = pre.next;
pre.next = next;
}
return dummyNode.next;
}
2. 两两交换链表中的节点’
使用虚拟头节点
首先移动到待反转节点的前一个位置
将新节点移动到前边
/**
* 方法3:直接根据两个指针的情况来设置
* 使用虚拟头节点,不断交换两个节点
* 交换完之后往后移动
*
* @param head
* @return
*/
public static ListNode swapPairs(ListNode head) {
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode, cur = dummyNode.next;
while (cur != null && cur.next != null) {
ListNode next = cur.next;
cur.next = next.next;
next.next = cur;
pre.next = next;
pre = pre.next.next;
cur = cur.next;
}
return dummyNode.next;
}
3. 链表加1
需要注意进位以及如果进位后位数不够了需要往前边补一位
/**
* 需要注意进位以及如果进位后位数不够了需要往前边补一位
* @param head
* @return
*/
public static ListNode plusOne(ListNode head) {
Stack<ListNode> stack = new Stack<>();
ListNode cur = head;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
int front = 0;
int add = 1;
ListNode dummyNode = new ListNode(0);
while (!stack.isEmpty() || front == 1) {
ListNode last = stack.isEmpty() ? new ListNode(0) : stack.pop();
int val = last.val + add + front;
front = val >= 10 ? 1 : 0;
last.val = val >= 10 ? val - 10 : val;
cur = new ListNode(last.val);
cur.next = dummyNode.next;
dummyNode.next = cur;
add = 0;
}
return dummyNode.next;
}
4. 链表加法
通过链表反转实现
需要注意进位以及如果进位后位数不够了需要往前边补一位
/**
* 方法2:通过链表反转来实现
* 先链表反转,然后按位相加判断进位
* 得到最终结果后,还需要再反转一次
* @param head1
* @param head2
* @return
*/
public static ListNode addInListByReverse(ListNode head1, ListNode head2) {
head1 = reverse(head1);
head2 = reverse(head2);
ListNode node1 = head1, node2 = head2;
ListNode res = new ListNode(-1);
ListNode node = res;
int pre = 0;
while (node1 != null || node2 != null) {
int val = pre;
if (node1 != null) {
val += node1.val;
node1 = node1.next;
}
if (node2 != null) {
val += node2.val;
node2 = node2.next;
}
pre = val >= 10 ? 1 : 0;
int temp = val >= 10 ? val - 10 : val;
node.next = new ListNode(temp);
node = node.next;
}
if (pre == 1) {
node.next = new ListNode(pre);
}
return reverse(res.next);
}