关于数据结构头尾插法有无头结点算法问题
关于数据结构里头插法无头结点,有头结点和尾插法有无头结点的问题,指针之类的区别我不是很清楚,能举例子详细说明吗?最好有代码对比。麻烦了,谢谢了。
头插法是指新结点加在链表头部的,尾插法是指新结点加在链表尾部的。 头结点是在链表的开始结点之前附加一个结点。它具有两个优点: ⒈由于开始结点的位置被存放在头结点的指针域中,所以在链表的第一个位置上的操作就和在表的其它位置上操作一致,无须进行特殊处理; ⒉无论链表是否为空,其头指针都是指向头结点的非空指针(空表中头结点的指针域空),因此空表和非空表的处理也就统一了。
#include #include #include using namespace std; typedef struct node{ char data; struct node *next; }Node; Node * CreateLinkBase(string & s){ //尾插法建立带头结点的链表 int num=s。
length(); Node *head,*pre,*p; head=(Node*)malloc(sizeof(Node)); head->next=NULL; pre=head; for(int i=0;inext=p; p->data=s[i]; p->next=NULL; pre=p; } return head; } Node * CreateLinkTop(string &s){ //头插法建立带头结点的链表 Node *head,*p; head=(Node*)malloc(sizeof(Node)); head->next=NULL; int len=s。
length(); for(int i=0;idata=s[i]; p->next=head->next; head->next=p; } return head; } Node *FindLink(char c,Node *head) //查询 { Node *temp=head; temp=head->next; do{ if(temp->data==c) { coutnext; }while(temp!=NULL); if(temp==NULL) coutnext; while(p->data!=NULL) { coutdata; if(p->next==NULL) break; else p=p->next; } coutnext->data==c) { temp->next=temp->next->next; coutnext; }while(temp!=NULL); } int main(){ //测试 string input; Node *head1,*head2; cout>input; cout>c; FindLink(c,head1); cout>d; DeleteLink(d,head1); system("pause"); return 0; }。
答:既然是带头结点的非空单链表,那删除首元结点还不简单么。 只要将头结点的指针域指向首元结点的下一个结点就行了,释放,就行了。 例如,L是头结点的指针,next是结...详情>>