赞
踩
- /**************头插法建立链表*******/
- void CreateListF(LinkList *&L,ElemType a[],int n)
- {
- int i;
- L = new LinkList;//注意LinkList()的区别
- L->next = NULL;
- L->data = n;//带头节点的,保存链表长度
- for (i = 0; i < n; i++)
- {
- LinkList *s = new LinkList;//创建临时节点
- s->data = a[i];
- s->next = L->next;
- L->next = s;
-
- }
- }
- /*************尾插法建立链表************/
- void CreateListR(LinkList *&L, ElemType a[], int n)
- {
- int i;
- LinkList *s, *r;
- L = new LinkList;
- L->data = n;//带头节点的,保存链表长度
- r = L;//r一直指向最后
- for (i = 0; i < n; i++)
- {
- s = new LinkList;
- s->data = a[i];
- r->next =s;
- r = s;
- }
- r->next = NULL;
- }
- /*带头结点的反转,用头插法的方法*/
- void rev1List(LinkList *&L)
- {
- LinkList *newlist, *cur,*next;
- newlist = new LinkList;
- newlist->next = NULL;
- cur = L->next;
- while (cur != NULL)
- {
- next = cur->next;
- cur->next = newlist->next;
- newlist->next = cur;
- cur = next;
- }
- L = newlist;
- }
- /*带头结点的反转,用指针的方法*/
- void rev2List(LinkList *&L)
- {
- if (L == NULL || L->next == NULL)//如果头结点为空或者头结点指向为空,链表长度为0
- return;
- LinkList *prev, *temp, *next;
- prev = NULL;
- temp = L->next;//指向第一个实际节点
- while (temp->next != NULL)//判断是否遍历完全
- {
- next = temp->next;
- temp->next = prev;//反转
- prev = temp;
- temp = next;
- }
- //last node
- temp->next = prev;
- L->next = temp;//temp是最后一个结点
- }
- //递归方式,不带头结点的链表,不太适用于带头节点的链表
- LinkList *reverseList(LinkList *head)
- {
- //如果链表为空或者链表中只有一个元素
- if (head == NULL || head->next == NULL)
- {
- return head;
- }
- else
- {
- //先反转后面的链表,走到链表的末端结点
- LinkList *newhead = reverseList(head->next);
- //再将当前节点设置为后面节点的后续节点
- head->next->next = head;
- head->next = NULL;
-
- return newhead;
- }
- }
- //还有一个本地反转法,begin和end
- //参考链接http://c.biancheng.net/view/8105.html
- //查找倒数第k个节点
- LinkList *lastNode(LinkList *head, int k)
- {
- LinkList *first = head;
- LinkList *second = head;
- for (int i = 0; i < k; i++)
- {
- first = first->next;
- }
- while (NULL == first)
- {
- first = first->next;
- second = second->next;
- }
- }
- LinkList* mergeTwoLists(LinkList* list1, LinkList* list2){
- if (list1 == NULL || list1->next == NULL)
- return list2;
- if (list2 == NULL || list2->next == NULL)
- return list1;
- struct LinkList *sp = list1->next;
- struct LinkList *prev = list1;
- struct LinkList *tmp;
- while (sp) {
- while (sp->val > list2->next->val){
- tmp = list2->next;
- list2->next = list2->next->next;//依次删除节点
- tmp->next = sp;
- prev->next = tmp;
- }
- prev = sp;
- sp = sp->next;
- }
- if (list2->next != NULL){
- prev->next = list2->next;
- }
- return list1;
- }
参考连接:
【链表】链表常见笔试题和面试题(C语言)_c语言链表经典笔试题-CSDN博客
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。