链表的常见操作,摘自《剑指offer》。
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
//LinkedListstruct ListNode{ int m_nValue; ListNode* m_pNext;};void AddToTail(ListNode** pHead, int value){ ListNode* pNew=new ListNode(); pNew->m_nValue=value; pNew->m_pNext=NULL; if(*pHead == NULL) *pHead=pNew; else { ListNode* p= *pHead; while(p=m_pNext != NULL) { p=p->m_pNext; } p->m_pNext=pNew; }}void RemoveNode(ListNode** pHead, int value){ if(pHead == NULL || *pHead == NULL) return; ListNode* pToDeleted=NULL; if((*pHead)->m_nValue == value) { pToDeleted=*pHead; *pHead=(*pHead)->m_pNext; }else { ListNode* p=*pHead; while(p->m_pNext != NULL && p->m_pNext->value!=NULL) p=p->m_pNext; if(p->m_pNext != NULL && p->m_pNext->value == value) { pToDeleted = p->m_pNext; p->m_pNext=->m_pNext->m_pNext; } } if(pToDeleted != NULL) { delete pToDeleted; pToDeleted = NULL; }}
1234567891011121314151617181920212223242526272829
// 从尾到头打印链表 迭代void PrintListReversingly_Itetatively(ListNode* pHead){ std::stack<ListNode*> nodes; ListNode* p=pHead; while(p!=NULL) { nodes.push(p); p=p->m_pNext; } while(!nodes.empty()) { p=node.top(); printf("%d \n", p->m_nValue); nodes.pop(); }}// 从尾到头打印链表 递归void PrintListReversingly_Recursively(ListNode* pHead){ if(pHead!=NULL) { if(pHead->m_pNext!=NULL) PrintListReversingly_Recursively(pHead->m_pNext); printf("%d \n", pHead->m_nValue); }}