在链表中找到第一个含有某值的节点并删除该节点。
在这里我创建的链表里,头节点是不包含有效数据的,它只是起一个辅助作用,真正的链表数据从首节点开始。
typedef struct Node
{
int data; //数据域
struct Node * pNext; //指针域
}NODE, *PNODE;
1: void RemoveNode(PNODE pHead, int val)
2: {
3: if(pHead == NULL || pHead->pNext == NULL)
4: return;
5:
6: PNODE pToBeDeleted = NULL;
7: PNODE pNode = pHead;
8:
9: while(pNode != NULL && pNode->pNext->data != val)
10: pNode = pNode->pNext;
11:
12: if(pNode != NULL && pNode->pNext->data == val)
13: {
14: pToBeDeleted = pNode->pNext;
15: pNode->pNext = pNode->pNext->pNext;
16: }
17:
18: if(pToBeDeleted != NULL)
19: {
20: free(pToBeDeleted);
21: pToBeDeleted = NULL;
22: }
23: }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
从尾到头打印链表。
这题最好让人想到的就是使用递归,结构比循环更为简单易懂,也更好进行掌握。
1: void printList_reverser(PNODE pHead)
2: {
3: if (pHead != NULL && pHead->pNext != NULL)
4: printList_reverser(pHead->pNext);
5:
6: printf("%d ", pHead->data);
7: }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }