单向不带头链表的使用
链表的创建:
typedef struct LNode {
SLDataType data;
struct LNode* next;
}LNode,*LinkList;
按位查找
LNode* GetElem(LinkList L, int i) {
int j = 1;
LNode* p = L->next;
if (i < 0)
return NULL;
if (i == 0)
return L;
while (p && j < i) {
p = p->next;
j++;
}
return p;
}
后插(将值为x的元素插入到第i个位置)
p=GetElen(L,i-1);
s->next=p->next;
p->next=s;
前插操作
s->next=p->next;
p->next=s;
tmp=p->data;
p->data=s->data;
s->data=tmp;
按值查找
LNode* LocateElem(LinkList l, SLDataType e) {
LNode* p = l->next;
while (p && p->data != e) {
p = p->next;
}
return p;
}
画图时应先画物理结构图在画逻辑结构图
链表的头插
//尾插
void SListPushBack(SLTNode** pphead, SLDataType x);
void SListPushBack(SLTNode** pphead, SLDataType x) {
SLTNode* newnode = BuySListNode(x);
if (*pphead == NULL) {
*pphead = newnode;
}
else {
//找尾结点的指针
SLTNode* tail = *pphead;
while (tail->next) {
tail = tail->next;
}
//将尾结点链接到新的结点
tail->next = newnode;
}
}
链表的尾插
void SListPushFront(SLTNode** pphead, SLDataType x) {
SLTNode* newnode = BuySListNode(x);
newnode->next = *pphead;
*pphead = newnode;
}
链表的头删
//头删
void SListPopFront(SLTNode** pphead);
void SListPopFront(SLTNode** pphead)
{
SLTNode* next = (*pphead)->next;
free(*pphead);
*pphead = next;
}
链表的尾删
//尾删
void SListPopBack(SLTNode** pphead);
void SListPopBack(SLTNode** pphead)
{
//链表为空
if (*pphead = NULL) {
return;
}
//只有一个结点
else if (*pphead) {
free(*pphead);
*pphead = NULL;
}
else {
SLTNode* prev = NULL;
SLTNode* tail = *pphead;
while (tail->next) {
prev = tail;
tail = tail->next;
}
free(tail);
prev->next = NULL;
}
}
链表的结点查找
SLTNode* SListFind(SLTNode* phead, SLDataType x);
SLTNode* SListFind(SLTNode* phead, SLDataType x)
{
SLTNode* cur=phead;
while (cur) {
if (cur->data == x) {
return cur;
}
cur = cur->next;
}
return NULL;
}
结点的创建
SLTNode* BuySListNode(SLDataType x) {
SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
newnode->data = x;
newnode->next = NULL;
return newnode;
}
在pos的前面插入x
//在pos的前面插入x
void SListInsert(SLTNode** pphead,SLTNode* pos, SLDataType x);
void SListInsert(SLTNode** pphead, SLTNode* pos, SLDataType x) {
if (pos == *pphead) {
SListPushFront(pphead, x);
}
else {
SLTNode* newnode = BuySListNode(x);
SLTNode* prev = *pphead;
while (prev->next != pos) {
prev = prev->next;
}
prev->next = newnode;
newnode->next = pos;
}
}
删除pos位置的值
void SListErase(SLTNode** pphead, SLTNode* pos) {
if (pos = *pphead) {
SListPopFront(pphead);
}
else {
SLTNode* prev = *pphead;
while (prev->next != pos) {
prev = prev->next;
}
prev->next = pos->next;
free(pos);
}
}