您的位置:首页 > 其它

链表的操作

2013-10-05 15:58 295 查看
    

    @1在链表操作中,如何判断删除的结点与头结点的关系?

在链表中
在链表头
在链表尾
    删除结点之后,结点指针变成野指针,此时应最好将其赋值为NULL;

//以O(1)的时间复杂度删除节点
struct listNode{
int value;
listNode *next;
};
void deleteNode(listNode * head,listNode * toBeDelete){
if(!head || !toBeDelete)
return ;
if(toBeDelete->next!=NULL){    //要删除的结点不是尾结点
listNode *pNext=toBeDelete->next;
toBeDelete->value=pNext->value;
toBeDelete->next=pNext->next;

delete pNext;
pNext=NULL;
}
else if(head==toBeDelete){    //链表只有一个结点,删除头结点
delete toBeDelete;
toBeDelete=NULL;
head=NULL;
}
else{    //链表中存在多个结点,删除尾结点
listNode *p=head;
while(p->next!=toBeDelete){
p=p->next;
}
p->next=NULL;
delete toBeDelete;
toBeDelete=NULL;
}
}


    @2如何求倒数第n个节点?

struct node{
int value;
node *next;
};

node* backwordn(node * head,int n){
if(head==NULL || n==0)
return NULL;
//get the length of array,
node *start=head;
int i=1;
//use for statement to loop array,cycle times ps the length
while(i<n){
if(start)
return NULL;
start=start->next;
++i;
}
node *wordn=head;
while(start->next){
start=start->next;
wordn=wordn->next;
}
return wordn;
}


    @3 反转单链表

node * reverse(node *head){
node *pNode=head;
node *pPreversed=NULL;
node *pPrev=NULL;
while(pNode){
node * pNext=pNode->next;
if(pNext)
pPreversed=pNode;
pNode->next=pPrev;
pPrev=pNode;
pNode=pNext;
}
return pPreversed;
}


    @4 将两个递增链表合并成一个链表

node *merge(node * head1,node * head2){
if(head1==NULL && head2==NULL)
return NULL;
else if(head1==NULL)
return head2;
else
return head1;
node *head=NULL;    //头结点,变量在递归函数中的调用,返回最外层的变量
if(head1->value<head2->value){
head=head1;
head->next=merge(head1->next,head2);
}
else{
head=head2;
head->next=merge(head2->next,head1);
}
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息