C语言学了这么久这是,指针什么的还是容易搞混,T_T
从链表中删除指定位置的节点
- 指针p指向要删除节点的上一个位置。
- 指针q指向要删除的节点,p指向要删除节点的下一个位置。
- 释放q。
typedef struct Node
{
int date;
struct Node *next;
}Node, *List;
void deleteList(List L, int n)
{
Node *p = L;
Node *q;
for(int i=0; i<n-1; i++) p = p->next; //要删除节点的上一位置
q = p->next; //指向要删除的节点
p->next = p->next->next; //指向要删除节点的下一位置
free(q); //释放q
}
链表反转操作
第一种反转方法需要两个额外的指针q, r.
1. q指向head的下一个结点, r指向q的下一结点。
2. q指向r的下一结点,r指向head的下一结点。
3. head指向r。
4. r重新指向q的下一结点。
void reverseList(List head)
{
Node *q = head->next;
Node *r = q->next;
while(r != NULL)
{
q->next = r->next;
r->next = head->next;
head->next = r;
r = q->next;
}
}
第二种方法是每次都将原第一个结点之后的那个结点放在list后面。
void reverseList2(List head)
{
Node *p, *q, *r;
p = q = r = head->next;
while(q->next != NULL)
q = q->next;
// printf("%d", q->date);
while(q != p)
{
head->next = p->next;
p->next = q->next;
q->next = p;
p = head->next;
printList(head);
}
}