插入
- 尾插法 【保留空白头结点和负责插的大臣】
- 头插法【只保留空白头结点即可】
两种头插法
第一种:在新链表设置一个头结点,从原来的链表取一个,插入新的链表头结点的后面。
public ListNode reverseList(ListNode head){
ListNode h = new ListNode(0);
while(head!=null){
ListNode t = head.next;
head.next = h.next;
h.next = head;
head = t;
}
return head.next;
}
第二种:在原来的链表中设置一个头结点。删除后面的节点插入到头结点的后面。因为第一个节点head已经插了,所以只需要删除插入n-1个节点,每次删除head后面的节点并插入头结点
特别适合反转链表中的一部分,如leetcode92
public ListNode reverseList(ListNode head){
if (head==null) return null;
ListNode h = new ListNode(0);
h.next = head;
//head为已经倒排部分的最后一个,还有没有进行删除插入的
while(head.next!=null){
//删除head后面的节点
ListNode remove = head.next;
head.next = remove.next;
//将删除节点插入已经倒排好的部分
remove.next = h.next;
h.next = remove;
}
return h.next;
}
第三种:在新链表设置一个头结点,从原来的链表取一个,插入新的链表充当头结点
ListNode newHead = null;
while(head!=null){
ListNode temp = head.next;
head.next = newHead;
newHead = head;
head = temp;
}
return newHead;
- java
//删除结点 ***删除结点 此时要构造头结点,防止删除第一个结点**
cur//为要删除的前一个结点
while (cur != null && cur.next != null)
{
if (满足条件) //cur为要删除的前一个结点
cur.next = cur.next.next;
else
cur = cur.next;
}
- python
**创建链表**
#尾插法
head=ListNode(0)
cur = head
//插入
cur.next = ListNode(2)
//移动大臣
cur=cur.next
return head.next
#头插法
head = ListNode(0)
node = ListNode(2)
//插入
node.next = head.next
head.next = node
return head.next
#删除结点***删除结点 此时要构造头结点,防止删除第一个结点**
cur = head #去火车车厢们巡视的大臣
while cur and cur.next: #不是None结点,也不是最后一个结点
if 满足条件:
cur.next = cur.next.next
else:
cur=cur.next;
#链表有多少结点
cur=head
num=0
while cur:
cur=cur.next
num+=1
- c++
**创建链表**
//尾插法
ListNode* head = new ListNode(0);//new会返回指针
ListNode* cur = head;//负责插的大臣,cur是不为空的结点
/*
ListNode head(0);//实例化一个类
ListNode* cur = &head;
*/
//插入是要在一个固定的结点后面插,才能得到一个链表,所以,先构造一个头
cur->next = new ListNode(2);
//移动大臣
cur = cur->next;
return head->next;//head指向的结点只是链表开始的固定头
//头插法
ListNode* head = new ListNode(0);
ListNode* node = new ListNode(0):
//插入
node->next = head->next;
head->next = node;
return head->next;
***删除结点 此时要构造头结点,防止删除第一个结点**
ListNode* cur = head;//去火车车厢们巡视的大臣
while (cur!=NULL && cur->next != NULL) //不是None结点,也不是最后一个结点
//不能去掉cur!=NULL,因为当其为NULL时,无->next
{
if (满足条件)//cur为要删除的前一个结点
cur->next = cur->next->next;
else
cur=cur->next;
}
***链表有多少结点**
int num=0;
ListNode* cur=head;
while (cur)
{
num+=1;
cur = cur->next;
}
注意
只有删除节点时,才需要ListNode temp = node.next记住后面的节点。