标签:
#include "stdafx.h" #include <malloc.h> #include <iostream> #include <stdio.h> #include <math.h> #include <stdlib.h> using namespace std; typedef int DataType; struct LNode{ DataType data; struct LNode *next; }; typedef struct LNode *LinkList; int getElem(LinkList L,int i,DataType *e) { //找到第i个元素并复制给e int j = 0; LinkList p = L->next; while(p&&j<i) { p = p->next; j++; } if(!p ||j>i) return -1; *e = p->data; return 1; } //在第i个位置插入e int insert(LinkList L,int i ,DataType e) { //先找到第i-1个节点 LinkList p = L,s; int j = 0; while( p && j<i-1) { p = p->next; j++; } if(!p ||j>i+1) return -1; //生成新节点 s = (LinkList)malloc(sizeof(struct LNode)); s->data = e; s->next = p->next; p->next = s; return 1; } int listDelete(LinkList L,int i,DataType *data) { int j =0; LinkList p = L,q; while(p->next&&j<i-1) { p=p->next; j++; } if(!p->next||j>i-1) return -1; q = p->next; p->next = q->next; *data = q->data; free(q); return 1; } /*int deleteByTail(LinkList *L)//位置并不好找 { LNode *p =(*L)->next; while(p->next != NULL) p =p->next; }*/ //在表头输入插入n个元素的值 /*int insertByHead(LinkList *L,int n) { //先建立一个带头结点的单链表 *L = (LinkList)malloc(sizeof(struct LNode)); (*L)->next =NULL; //循环输入插入 LinkList p ; for(int i=n;i>0;i--) { //生成新的节点 p = (LinkList)malloc(sizeof(struct LNode)); scanf("%d",&p->data); p->next = (*L)->next; (*L)->next = p; } }*/ int insertByTail(LNode **head,DataType data) { /*LNode *p,*temp; if((*L)->next != NULL) { *p = (*L)->next->next; } //LNode *p = (*L)->next,*temp; temp = (LNode*)malloc(sizeof(struct LNode)); temp ->data = data; while(p->next != NULL) p = p->next; p->next = temp; temp->next = NULL; return 0;*/ //判断链表是否为空 LNode *phead = *head; LNode *pTemp = new LNode; pTemp = phead; LNode *insert_node = new LNode; insert_node->data = data; insert_node ->next = nullptr; while(phead != nullptr) phead = phead->next;//这句话会报错 phead->next = insert_node; *head = pTemp; return 1; } int showList(LinkList L) { int num = 0; LinkList p =L->next; while(p) { if(num)//如果不是表中的第一个元素 { putchar(‘ ‘); } num++; printf("%d",p->data); p= p->next; } if(num ==0) return 0; else return num; } /*void main() {//最后运行不出结果 LinkList L; insertByTail(&L,1); insertByTail(&L,2); showList(L); }*/
标签:
原文地址:http://www.cnblogs.com/waiwai4701/p/4207935.html