值得一提的是在第三题的归并排序里面设置了一个dummy Node 可以让程序更加的简洁。
1 (30分)
typedef int Node_entry;
struct Node {
Node_entry data;
struct Node *next;
};
void delredundant(struct Node * head)
{
struct Node *p,*q,*s;
for(p=head;p!=0;p=p->next)
{
for(q=p->next,s=p;q!=0; )
if (q->data==p->data)
{
s->next=q->next;
free(q);
q=s->next;
}
else {
s=q; // s作为q的前一个节点的指针。
q=q->next;
}
}
}
2. (30分)
typedef int Node_entry;
struct Node {
Node_entry data;
struct Node *next;
};
1->2->3-> 4->5
void Inverse (struct Node ** head){
// 如果用一个*的时候,则参数无法传递进来。
struct Node *h=*head;
struct Node *pre, *tmp;
if(h==NULL)return;
pre=NULL;
tmp=h->next;
while(tmp!=NULL){
h->next=pre;
pre=h;
h=tmp;
tmp=tmp->next;
}
h->next=pre;
*head=h;
}
3. (40分)
typedef int Node_entry;
struct Node {
Node_entry entry;
struct Node *next;
};
struct Node * merge(struct Node *first, struct Node *second)
{
struct Node *last_sorted; // points to the last node of sorted list
struct Node combined; // dummy first node, points to merged list
//这是一个哑节点
last_sorted = &combined; //有这样的一个节点可以为后面节省一些判断的语句!!!好聪明的方法啊!!!可以让代码变得简洁许多!!!
while (first != NULL && second != NULL) { // Attach node with smaller key
if (first->entry <= second->entry) {
last_sorted->next = first;
last_sorted = first;
first = first->next; // Advance to the next unmerged node.
}
else {
last_sorted->next = second;
last_sorted = second;
second = second->next;
}
}
// After one list ends, attach the remainder of the other.
if (first == NULL)
last_sorted->next = second;
else
last_sorted->next = first;
return combined.next;
}