ListNode dummynode = new ListNode(-1);
dummynode.next = head; //设置一个虚拟头节点
删除链表元素
链表逆置: 使用双指针法,只需要调整指针的指向,不需要新建空链表,代码:
public ListNode reverseList(ListNode head) {
//双指针
ListNode cur = head;
ListNode pre = null;
ListNode temp = null;
while (cur != null) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
删除链表的倒数第 n 个结点,并且返回链表的头结点。
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummynode = new ListNode(-1);
dummynode.next = head;
int size = 0;
ListNode cur = head;
//计算链表的长度
while (cur != null) {
size++;
cur = cur.next;
}
//倒数第n个节点的下标:
int index = size - n;
ListNode pre = dummynode;
//删除下标为index的元素
for (int i = 0; i < index; i++) {
pre = pre.next;
}
size--;
pre.next = pre.next.next;
return dummynode.next;
}