NodeImpl * NodeImpl::appendChild(NodeImpl *newChild)
{
    return insertBefore(newChild, null);
};
Esempio n. 2
0
DOMNode * DOMParentNode::appendChild(DOMNode *newChild)
{
    return insertBefore(newChild, 0);
}
Esempio n. 3
0
DOMNode *DOMParentNode::insertBefore(DOMNode *newChild, DOMNode *refChild) {
    //not really in the specs, but better than nothing
    if(newChild==NULL)
        throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0, GetDOMParentNodeMemoryManager);

    DOMNodeImpl *thisNodeImpl = castToNodeImpl(this);
    if (thisNodeImpl->isReadOnly())
        throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR, 0, GetDOMParentNodeMemoryManager);

    if (newChild->getOwnerDocument() != fOwnerDocument)
        throw DOMException(DOMException::WRONG_DOCUMENT_ERR, 0, GetDOMParentNodeMemoryManager);

    // Prevent cycles in the tree
    //only need to do this if the node has children
    if(newChild->hasChildNodes()) {
        bool treeSafe=true;
        for(DOMNode *a=castToNode(this)->getParentNode();
            treeSafe && a!=0;
            a=a->getParentNode())
            treeSafe=(newChild!=a);
        if(!treeSafe)
            throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0, GetDOMParentNodeMemoryManager);
    }

    // refChild must in fact be a child of this node (or 0)
    if (refChild!=0 && refChild->getParentNode() != castToNode(this))
        throw DOMException(DOMException::NOT_FOUND_ERR,0, GetDOMParentNodeMemoryManager);

    // if the new node has to be placed before itself, we don't have to do anything 
    // (even worse, we would crash if we continue, as we assume they are two distinct nodes)
    if (refChild!=0 && newChild->isSameNode(refChild))
        return newChild;

    if (newChild->getNodeType() == DOMNode::DOCUMENT_FRAGMENT_NODE)
    {
        // SLOW BUT SAFE: We could insert the whole subtree without
        // juggling so many next/previous pointers. (Wipe out the
        // parent's child-list, patch the parent pointers, set the
        // ends of the list.) But we know some subclasses have special-
        // case behavior they add to insertBefore(), so we don't risk it.
        // This approch also takes fewer bytecodes.

        // NOTE: If one of the children is not a legal child of this
        // node, throw HIERARCHY_REQUEST_ERR before _any_ of the children
        // have been transferred. (Alternative behaviors would be to
        // reparent up to the first failure point or reparent all those
        // which are acceptable to the target node, neither of which is
        // as robust. PR-DOM-0818 isn't entirely clear on which it
        // recommends?????

        // No need to check kids for right-document; if they weren't,
        // they wouldn't be kids of that DocFrag.
        for(DOMNode *kid=newChild->getFirstChild(); // Prescan
              kid!=0;
              kid=kid->getNextSibling())
        {
            if (!DOMDocumentImpl::isKidOK(castToNode(this), kid))
              throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0, GetDOMParentNodeMemoryManager);
        }
        while(newChild->hasChildNodes())     // Move
            insertBefore(newChild->getFirstChild(),refChild);
    }

    else if (!DOMDocumentImpl::isKidOK(castToNode(this), newChild))
        throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0, GetDOMParentNodeMemoryManager);

    else
    {
        DOMNode *oldparent=newChild->getParentNode();
        if(oldparent!=0)
            oldparent->removeChild(newChild);

        // Attach up
        castToNodeImpl(newChild)->fOwnerNode = castToNode(this);
        castToNodeImpl(newChild)->isOwned(true);

        // Attach before and after
        // Note: fFirstChild.previousSibling == lastChild!!
        if (fFirstChild == 0) {
            // this our first and only child
            fFirstChild = newChild;
            castToNodeImpl(newChild)->isFirstChild(true);
            // castToChildImpl(newChild)->previousSibling = newChild;
            DOMChildNode *newChild_ci = castToChildImpl(newChild);
            newChild_ci->previousSibling = newChild;
        } else {
            if (refChild == 0) {
                // this is an append
                DOMNode *lastChild = castToChildImpl(fFirstChild)->previousSibling;
                castToChildImpl(lastChild)->nextSibling = newChild;
                castToChildImpl(newChild)->previousSibling = lastChild;
                castToChildImpl(fFirstChild)->previousSibling = newChild;
            } else {
                // this is an insert
                if (refChild == fFirstChild) {
                    // at the head of the list
                    castToNodeImpl(fFirstChild)->isFirstChild(false);
                    castToChildImpl(newChild)->nextSibling = fFirstChild;
                    castToChildImpl(newChild)->previousSibling = castToChildImpl(fFirstChild)->previousSibling;
                    castToChildImpl(fFirstChild)->previousSibling = newChild;
                    fFirstChild = newChild;
                    castToNodeImpl(newChild)->isFirstChild(true);
                } else {
                    // somewhere in the middle
                    DOMNode *prev = castToChildImpl(refChild)->previousSibling;
                    castToChildImpl(newChild)->nextSibling = refChild;
                    castToChildImpl(prev)->nextSibling = newChild;
                    castToChildImpl(refChild)->previousSibling = newChild;
                    castToChildImpl(newChild)->previousSibling = prev;
                }
            }
        }
    }

    changed();

    if (this->getOwnerDocument() != 0) {
        Ranges* ranges = ((DOMDocumentImpl *)this->getOwnerDocument())->getRanges();
        if ( ranges != 0) {
            XMLSize_t sz = ranges->size();
            if (sz != 0) {
                for (XMLSize_t i =0; i<sz; i++) {
                    ranges->elementAt(i)->updateRangeForInsertedNode(newChild);
                }
            }
        }
    }

    return newChild;
}
//Add the word "w" to the first of the doubly linked list
void DoublyLinkedList::add(string w)
{   insertBefore(w,head);
}
void MediaControlsChromium::insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement> textTrackContainer)
{
    // Insert it before the first controller element so it always displays behind the controls.
    // In the Chromium case, that's the enclosure element.
    insertBefore(textTrackContainer, m_enclosure, ASSERT_NO_EXCEPTION, AttachLazily);
}
Esempio n. 6
0
NodeImpl *ParentNode::insertBefore(NodeImpl *newChild, NodeImpl *refChild) {

    bool errorChecking = ownerDocument->getErrorChecking();

    if (newChild->isDocumentFragmentImpl()) {
        // SLOW BUT SAFE: We could insert the whole subtree without
        // juggling so many next/previous pointers. (Wipe out the
        // parent's child-list, patch the parent pointers, set the
        // ends of the list.) But we know some subclasses have special-
        // case behavior they add to insertBefore(), so we don't risk it.
        // This approch also takes fewer bytecodes.

        // NOTE: If one of the children is not a legal child of this
        // node, throw HIERARCHY_REQUEST_ERR before _any_ of the children
        // have been transferred. (Alternative behaviors would be to
        // reparent up to the first failure point or reparent all those
        // which are acceptable to the target node, neither of which is
        // as robust. PR-DOM-0818 isn't entirely clear on which it
        // recommends?????

        // No need to check kids for right-document; if they weren't,
        // they wouldn't be kids of that DocFrag.
        if (errorChecking) {
            for (NodeImpl *kid = newChild->getFirstChild(); // Prescan
                 kid != null; kid = kid->getNextSibling()) {

                if (!DocumentImpl::isKidOK(this, kid)) {
                    throw DOM_DOMException(
                                       DOM_DOMException::HIERARCHY_REQUEST_ERR,
                                       null);
                }
            }
        }

        while (newChild->hasChildNodes()) {    // Move
            insertBefore(newChild->getFirstChild(),refChild);
        }
        return newChild;
    }

    // it's a no-op if refChild is the same as newChild
    if (refChild == newChild) {
        return newChild;
    }

    if (errorChecking) {
        if (isReadOnly()) {
            throw DOM_DOMException(
                                 DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR,
                                 null);
        }
        if (newChild->getOwnerDocument() != ownerDocument) {
            throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR, null);
        }
        if (!DocumentImpl::isKidOK(this, newChild)) {
            throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,
                                   null);
        }
        // refChild must be a child of this node (or null)
        if (refChild != null && refChild->getParentNode() != this) {
            throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null);
        }

        // Prevent cycles in the tree
        // newChild cannot be ancestor of this Node,
        // and actually cannot be this
        bool treeSafe = true;
        for (NodeImpl *a = this; treeSafe && a != null; a = a->getParentNode())
        {
            treeSafe = (newChild != a);
        }
        if (!treeSafe) {
            throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,
                                   null);
        }
    }

    // Convert to internal type, to avoid repeated casting
    ChildNode * newInternal = (ChildNode *)newChild;

    NodeImpl *oldparent = newInternal->getParentNode();
    if (oldparent != null) {
        oldparent->removeChild(newInternal);
    }

    // Convert to internal type, to avoid repeated casting
    ChildNode *refInternal = (ChildNode *)refChild;

    // Attach up
    newInternal->ownerNode = this;
    newInternal->isOwned(true);

    // Attach before and after
    // Note: firstChild.previousSibling == lastChild!!
    if (firstChild == null) {
        // this our first and only child
        firstChild = newInternal;
        newInternal->isFirstChild(true);
        newInternal->previousSibling = newInternal;
    }
    else {
        if (refInternal == null) {
            // this is an append
            ChildNode *lastChild = firstChild->previousSibling;
            lastChild->nextSibling = newInternal;
            newInternal->previousSibling = lastChild;
            firstChild->previousSibling = newInternal;
        }
        else {
            // this is an insert
            if (refChild == firstChild) {
                // at the head of the list
                firstChild->isFirstChild(false);
                newInternal->nextSibling = firstChild;
                newInternal->previousSibling = firstChild->previousSibling;
                firstChild->previousSibling = newInternal;
                firstChild = newInternal;
                newInternal->isFirstChild(true);
            }
            else {
                // somewhere in the middle
                ChildNode *prev = refInternal->previousSibling;
                newInternal->nextSibling = refInternal;
                prev->nextSibling = newInternal;
                refInternal->previousSibling = newInternal;
                newInternal->previousSibling = prev;
            }
        }
    }

    changed();

    // update cached length if we have any
    if (fCachedLength != -1) {
        fCachedLength++;
    }
    if (fCachedChildIndex != -1) {
        // if we happen to insert just before the cached node, update
        // the cache to the new node to match the cached index
        if (fCachedChild == refInternal) {
            fCachedChild = newInternal;
        }
        else {
            // otherwise just invalidate the cache
            fCachedChildIndex = -1;
        }
    }

    if (this->getOwnerDocument() != null) {
        typedef RefVectorOf<RangeImpl> RangeImpls;
        RangeImpls* ranges = this->getOwnerDocument()->getRanges();
        if ( ranges != null) {
            unsigned int sz = ranges->size();
            for (unsigned int i =0; i<sz; i++) {
                ranges->elementAt(i)->updateRangeForInsertedNode(newInternal);
            }
        }
    }

    return newInternal;
};
Esempio n. 7
0
void LList<T>::insertEnd(const T &newDAta){
    insertBefore(newDAta, tail);
}
Esempio n. 8
0
/**
 * Inserts the given Object pointer as the item just after refItem.
 * If refItem is a null pointer the Object will be inserted at the
 * beginning of the txList (ie, insert after nothing).
 * This method assumes refItem is a member of this list, and since this
 * is a private method, I feel that's a valid assumption
 **/
nsresult txList::insertAfter(void* objPtr, ListItem* refItem) {
  //-- if refItem == null insert at front
  if (!refItem) return insertBefore(objPtr, firstItem);
  return insertBefore(objPtr, refItem->nextItem);
}  //-- insertAfter
Esempio n. 9
0
Node *
Attr::internalInsertBefore(Node * newChild,
			   Node * refChild)
  throw(DOMException)
{
  Document * owner = getOwnerDocument();

  if (newChild == refChild) {
    refChild = refChild->getNextSibling();
    removeChild(newChild);
    insertBefore(newChild, refChild);
    return newChild;
  }
  if (isReadOnly())
    throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR);
  if (newChild->getOwnerDocument() != owner)
    throw DOMException(DOMException::WRONG_DOCUMENT_ERR);
  if (refChild != null && refChild->getParentNode() != this)
    throw DOMException(DOMException::NOT_FOUND_ERR);
  if (newChild != null &&
      newChild->getNodeType() != Node::TEXT_NODE)
    throw DOMException(DOMException::NOT_SUPPORTED_ERR);

  Text * newInternal = dynamic_cast<Text*>(newChild);

  Node * oldparent = newInternal->getParentNode();

  if (oldparent != null)
    oldparent->removeChild(newInternal);

  Text * refInternal = dynamic_cast<Text*>(refChild);

  newInternal->ownerNode = this;
  newInternal->isOwned(true);

  if (text == null) {
    text = newInternal;
    newInternal->isFirstChild(true);
    newInternal->previousSibling = newInternal;
  }
  else {
    if (refInternal == null) {
      ChildNode * lastChild = text->previousSibling;
      lastChild->nextSibling = newInternal;
      newInternal->previousSibling = lastChild;
      text->previousSibling = newInternal;
    }
    else {
      if (refChild == text) {
	text->isFirstChild(false);
	newInternal->nextSibling = text;
	newInternal->previousSibling = text->previousSibling;
	text->previousSibling = newInternal;
	text = newInternal;
	newInternal->isFirstChild(true);
      }
      else {
	ChildNode * prev = refInternal->previousSibling;
	newInternal->nextSibling = refInternal;
	refInternal->previousSibling = newInternal;
	newInternal->previousSibling = prev;
      }
    }
  }
  changed();
  return newChild;
}
Esempio n. 10
0
UEFITool::UEFITool(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::UEFITool), 
version(tr("0.20.4"))
{
    clipboard = QApplication::clipboard();

    // Create UI
    ui->setupUi(this);
    searchDialog = new SearchDialog(this);
    ffsEngine = NULL;

    // Set window title
    this->setWindowTitle(tr("UEFITool %1").arg(version));

    // Connect signals to slots
    connect(ui->actionOpenImageFile, SIGNAL(triggered()), this, SLOT(openImageFile()));
    connect(ui->actionSaveImageFile, SIGNAL(triggered()), this, SLOT(saveImageFile()));
    connect(ui->actionSearch, SIGNAL(triggered()), this, SLOT(search()));
    connect(ui->actionExtract, SIGNAL(triggered()), this, SLOT(extractAsIs()));
    connect(ui->actionExtractBody, SIGNAL(triggered()), this, SLOT(extractBody()));
    connect(ui->actionInsertInto, SIGNAL(triggered()), this, SLOT(insertInto()));
    connect(ui->actionInsertBefore, SIGNAL(triggered()), this, SLOT(insertBefore()));
    connect(ui->actionInsertAfter, SIGNAL(triggered()), this, SLOT(insertAfter()));
    connect(ui->actionReplace, SIGNAL(triggered()), this, SLOT(replaceAsIs()));
    connect(ui->actionReplaceBody, SIGNAL(triggered()), this, SLOT(replaceBody()));
    connect(ui->actionRemove, SIGNAL(triggered()), this, SLOT(remove()));
    connect(ui->actionRebuild, SIGNAL(triggered()), this, SLOT(rebuild()));
    connect(ui->actionMessagesCopy, SIGNAL(triggered()), this, SLOT(copyMessage()));
    connect(ui->actionMessagesCopyAll, SIGNAL(triggered()), this, SLOT(copyAllMessages()));
    connect(ui->actionMessagesClear, SIGNAL(triggered()), this, SLOT(clearMessages()));
    connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(about()));
    connect(ui->actionAboutQt, SIGNAL(triggered()), this, SLOT(aboutQt()));
    connect(ui->actionQuit, SIGNAL(triggered()), this, SLOT(exit()));
    connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(writeSettings()));

    // Enable Drag-and-Drop actions
    this->setAcceptDrops(true);

    // Set current directory
    currentDir = ".";

    // Set monospace font for some controls
    QFont font("Courier New", 10);
#if defined Q_OS_OSX
    font = QFont("Menlo", 10);
#elif defined Q_OS_WIN
    font = QFont("Consolas", 9);
#endif
    ui->infoEdit->setFont(font);
    ui->messageListWidget->setFont(font);
    ui->structureTreeView->setFont(font);
    searchDialog->ui->guidEdit->setFont(font);
    searchDialog->ui->hexEdit->setFont(font);

    // Initialize non-persistent data
    init();

    // Read stored settings
    readSettings();
}
Esempio n. 11
0
int main(int argc, char **argv) {
	dlist *list;
	dlist *list2;
	dlist *list3;
	dlist *list4;
	int choice;
	int i = 0;
	int numData;
	Node *p;
	FILE *fin, *fout;
	int select = 0;
	int startFrom, numSplit; // where to split and the length of splitting list
	char fileName[15]; //file name for output data
	char textName1[20], textName2[20]; // file name for split lists

	char sections [MAX][40] = {"Import from phonebook.dat", "Display (traverse)", "Add new contact (insert before/after)",
	                           "Insert a position" , "Delete a position", "Delete current",
	                           "Delete first", "Search and Update", "Divide and Extract",
	                           "Reverse list", "Save to file", "Count max identical phone numbers", "Exit (free)"
	                          };


	do {
		choice = getMenu(sections, MAX);
		switch (choice) {
		case 1:

			// if ((fin = fopen(argv[1], "r")) == NULL)
			// {
			// 	printf("Can't open file %s\n", argv[1]);
			// 	exit(1);
			// }
			// if ((fout = fopen(argv[2], "wb")) == NULL)
			// {
			// 	printf("Can't open file %s\n", argv[2]);
			// 	exit(1);
			// }

			// numData = importDB(fin, fout);

			// fclose(fin);
			// fclose(fout);

			list = iniList(list);
			list2 = iniList(list2);
			list3 = iniList(list3);
			list4 = iniList(list4);
			if ((fin = fopen(argv[1], "rb")) == NULL)
			{
				printf("Can't open file %s\n", argv[1]);
				exit(1);
			}
			fseek(fin, 0, SEEK_END);
			numData = ftell(fin) / sizeof(element_type);
			rewind(fin);
			result = import(fin, numData);
			for (i = 0; i < result; ++i)
				insertEnd(contact[i], list);
			// printData();
			fclose(fin);
			break;
		case 2:
			traverse(list);
			break;
		case 3:
			printf("Enter 0 to insert before, 1 to insert after: ");
			scanf("%d", &select);
			while (getchar() != '\n');
			if (select == 0)
				insertBefore(list->root, typeHand(), list);
			else
				insertEnd(typeHand(), list);
			break;
		case 4: printf("Position to insert after (1 means root element): ");
			scanf("%d", &select);
			printf("Type in the data to insert\n");
			while (getchar() != '\n');
			if (select < numData)
				insertAfter(locateNode(select, list), typeHand(), list);
			else
				insertEnd(typeHand(), list);
			break;
		case 5: printf("Position to delete: (1 means root element)");
			scanf("%d", &select);
			delNode(locateNode(select, list), list);
			break;
		case 6: delNode(list->cur, list);
			break;
		case 7: delNode(list->root, list);
			break;
		case 8: searchName();
			while (1) {

				printf("Update for position number (type -1 to stop updating): ");
				scanf("%d", &select);
				while (getchar() != '\n');
				if (select == -1)
					break;

				insertAfter(locateNode(select, list), typeHand(), list);
				delNode(locateNode(select, list), list);
				printf("Update success\n");
			}
			break;
		case 9:
			printf("The length of the list is %d\n", listLength(list));
			printf("Type in where to start (range from 1 to end of the list): ");
			scanf("%d", &startFrom);
			printf("Length of spliting: ");
			scanf("%d", &numSplit);
			if (listLength(list) > startFrom + numSplit)
				splitList(startFrom, numSplit, list, list2, list3);
			else
				splitList(startFrom, listLength(list) - startFrom, list, list2, list3);
			while (getchar() != '\n');
			printf("Now type in 2 file name to save the new lists\n");
			printf("File 1: ");
			scanf("%s", textName1);
			printf("File 2: ");
			scanf("%s", textName2);
			checkList(list2, textName1); //result of splitList
			checkList(list3, textName2);
			break;
		case 10:
			reverseList(list);
			break;
		case 11:
			printf("Type in the file name\n");
			scanf("%s", fileName);
			if ((fout = fopen(fileName, "w + t")) == NULL)
			{
				printf("Can't open file %s\n", fileName);
				exit(1);
			}
			savetoFile(fout, list);
			break;
		case 12:
			list4 = countsameNum(list, list4);
			printf("After spliting, the new list with identical numbers: \n");
			p = list4->root;
			while ( p != NULL ) {
				printf("Node with phone number: %s, address %p\n", p->element.tel, p);
				p = p->next;
			}
			break;
		case MAX:
			freeList(list);
			freeList(list2);
			freeList(list3);
			freeList(list4);
			exit(1);
			break;
		default: printf("Invalid choice. It must be from 1 to %d\n", MAX); break;
		}
	} while (choice != MAX);
	return 0;
}
Esempio n. 12
0
Node* Node::replaceChild(Node *newChild, Node *oldChild)
{
	ASSERT(0);
#if 0
	ASSERT(newChild != NULL);
	ASSERT(oldChild != NULL);
	ASSERT(pVal != NULL);
	if (newChild == NULL) return E_INVALIDARG;
	if (oldChild == NULL) return E_INVALIDARG;
	if (pVal == NULL) return E_POINTER;

	if (TRUE)
	{
		CComQIPtr<ILDOMDocumentFragment, &IID_ILDOMDocumentFragment> fragment((IUnknown*)newChild);
		if (fragment)
		{
			CComPtr<ILDOMNode> beforeChild;
			oldChild->get_nextSibling(&beforeChild);

			thisNode->removeChild(oldChild, pVal);

			CComPtr<ILDOMNode> child;
			fragment->get_firstChild(&child);
			while (child)
			{
				CComPtr<ILDOMNode> nextSibling;
				child->get_nextSibling(&nextSibling);

				insertNode(thisNode, child, beforeChild, NULL);

				child = nextSibling;
			}
		}
		else
		{
			CComPtr<ILDOMNode> beforeChild;
			oldChild->get_nextSibling(&beforeChild);

			thisNode->removeChild(oldChild, pVal);

			insertBefore(thisNode, newChild, CComVariant(beforeChild), NULL);
		}
	}
	else
	{
#if 0
		for (int i = 0; i < m_childNodes->m_items.GetSize(); i++)
		{
			if (m_childNodes->m_items[i] == oldChild)
			{
				newChild->AddRef();
				m_childNodes->m_items[i] = newChild;

				*pVal = oldChild;
			}
		}
#endif
	}

	return S_OK;
#endif
	return NULL;
}
Esempio n. 13
0
int main (int argc, char * argv[]) {

   int n = 0;
   int lineNumber = 0;
   FILE *in, *out;
   char line[MAX_LEN];

   List L = newList();

   // check command line for correct number of arguments
   if( argc != 3 ){
     printf("Usage: %s <input file> <output file>\n", argv[0]);
     exit(1);
   }

   // open files for reading and writing 
   in = fopen(argv[1], "r");
   if( in==NULL ){
     printf("Unable to open file %s for reading\n", argv[1]);
     exit(1);
   }
   while( fgets(line, MAX_LEN, in) != NULL ) {
      n++;
   }
   fclose(in);
   
   char* lines[n];

   in = fopen(argv[1], "r");
   while( fgets(line, MAX_LEN, in) != NULL) {
      lines[lineNumber] = strdup(line);
      if(lineNumber > 0) {
         moveTo(L, lineNumber-1);
         int i = lineNumber - 1;
         char* tmp;
         tmp = lines[lineNumber];
         while(i > 0 && strcmp(tmp, lines[getElement(L)])<0) {
            movePrev(L);
            i--;
         }
         if(strcmp(tmp, lines[getElement(L)])<0) 
            insertBefore(L, lineNumber);
         else
            insertAfter(L, lineNumber);
      } else {
         append(L, lineNumber);
      }
      lineNumber++;
   }
   fclose(in);

   out = fopen(argv[2], "w");
   if( out==NULL ){
     printf("Unable to open file %s for writing\n", argv[2]);
     exit(1);
   }

   moveTo(L, 0);
   for(int i = 0; i < n; i++) {
      fprintf(out, lines[getElement(L)]);
      moveNext(L);
   }
   
   for(int i = 0; i < n; i++) {
      free(lines[i]);
   }

   freeList(&L);
   fclose(out);

   return(0);

}
Esempio n. 14
0
DOMNode *XPathDocumentImpl::insertBefore(DOMNode *newChild, DOMNode *refChild)
{
    // if the newChild is a documenttype node created from domimplementation, set the ownerDoc first
    if ((newChild->getNodeType() == DOMNode::DOCUMENT_TYPE_NODE) && !newChild->getOwnerDocument())
        ((DOMDocumentTypeImpl*)newChild)->setOwnerDocument(this);

    if(newChild==NULL)
        throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0, getMemoryManager());

    DOMNodeImpl *thisNodeImpl = castToNodeImpl(this);
    if (thisNodeImpl->isReadOnly())
        throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR, 0, getMemoryManager());

    DOMNode* thisNode = castToNode(&fParent);
    if (newChild->getOwnerDocument() != thisNode)
        throw DOMException(DOMException::WRONG_DOCUMENT_ERR, 0, getMemoryManager());

    // refChild must in fact be a child of this node (or 0)
    if (refChild!=0 && refChild->getParentNode() != thisNode)
        throw DOMException(DOMException::NOT_FOUND_ERR,0, getMemoryManager());

    // if the new node has to be placed before itself, we don't have to do anything 
    // (even worse, we would crash if we continue, as we assume they are two distinct nodes)
    if (refChild!=0 && newChild->isSameNode(refChild))
        return newChild;

    if (newChild->getNodeType() == DOMNode::DOCUMENT_FRAGMENT_NODE)
    {
        // SLOW BUT SAFE: We could insert the whole subtree without
        // juggling so many next/previous pointers. (Wipe out the
        // parent's child-list, patch the parent pointers, set the
        // ends of the list.) But we know some subclasses have special-
        // case behavior they add to insertBefore(), so we don't risk it.
        // This approch also takes fewer bytecodes.

        while(newChild->hasChildNodes())     // Move
            insertBefore(newChild->getFirstChild(),refChild);
    }

    else
    {
        DOMNode *oldparent=newChild->getParentNode();
        if(oldparent!=0)
            oldparent->removeChild(newChild);

        // Attach up
        castToNodeImpl(newChild)->fOwnerNode = thisNode;
        castToNodeImpl(newChild)->isOwned(true);

        // Attach before and after
        // Note: fFirstChild.previousSibling == lastChild!!
        if (fParent.fFirstChild == 0) {
            // this our first and only child
            fParent.fFirstChild = newChild;
            castToNodeImpl(newChild)->isFirstChild(true);
            // castToChildImpl(newChild)->previousSibling = newChild;
            DOMChildNode *newChild_ci = castToChildImpl(newChild);
            newChild_ci->previousSibling = newChild;
        } else {
            if (refChild == 0) {
                // this is an append
                DOMNode *lastChild = castToChildImpl(fParent.fFirstChild)->previousSibling;
                castToChildImpl(lastChild)->nextSibling = newChild;
                castToChildImpl(newChild)->previousSibling = lastChild;
                castToChildImpl(fParent.fFirstChild)->previousSibling = newChild;
            } else {
                // this is an insert
                if (refChild == fParent.fFirstChild) {
                    // at the head of the list
                    castToNodeImpl(fParent.fFirstChild)->isFirstChild(false);
                    castToChildImpl(newChild)->nextSibling = fParent.fFirstChild;
                    castToChildImpl(newChild)->previousSibling = castToChildImpl(fParent.fFirstChild)->previousSibling;
                    castToChildImpl(fParent.fFirstChild)->previousSibling = newChild;
                    fParent.fFirstChild = newChild;
                    castToNodeImpl(newChild)->isFirstChild(true);
                } else {
                    // somewhere in the middle
                    DOMNode *prev = castToChildImpl(refChild)->previousSibling;
                    castToChildImpl(newChild)->nextSibling = refChild;
                    castToChildImpl(prev)->nextSibling = newChild;
                    castToChildImpl(refChild)->previousSibling = newChild;
                    castToChildImpl(newChild)->previousSibling = prev;
                }
            }
        }
    }

    changed();

    Ranges* ranges = getRanges();
    if ( ranges != 0) {
        XMLSize_t sz = ranges->size();
        if (sz != 0) {
            for (XMLSize_t i =0; i<sz; i++) {
                ranges->elementAt(i)->updateRangeForInsertedNode(newChild);
            }
        }
    }

    // If insert succeeded, cache the kid appropriately
    if(newChild->getNodeType() == DOMNode::ELEMENT_NODE)
        fMyDocElement=(DOMElement *)newChild;
    else if(newChild->getNodeType() == DOMNode::DOCUMENT_TYPE_NODE)
        fMyDocType=(DOMDocumentType *)newChild;

    return newChild;
}
Esempio n. 15
0
int main(int argc, char* argv[]){
   
   
   FILE *out;

   out = fopen(argv[2], "w");



   List A = newList();
   List B = newList();
   List C = NULL;
   int i;

   for(i=1; i<=5; i++){
      append(A,i);
      prepend(B,i);
   }

   printList(out,A); 
   printf("\n");
   printList(stdout,B); 
   printf("\n");

   for(moveTo(A,0); getIndex(A)>=0; moveNext(A)){
      printf("%d ", getElement(A));
   }
   printf("\n");
   for(moveTo(B,length(B)-1); getIndex(B)>=0; movePrev(B)){
      printf("%d ", getElement(B));
   }
   printf("\n");

   C = copyList(A);
   printf("%s\n", equals(A,B)?"true":"false");
   printf("%s\n", equals(B,C)?"true":"false");
   printf("%s\n", equals(C,A)?"true":"false");

   printf("A's front = %d\n",    front(A));
   printf("A's back = %d\n",    back(A));
   deleteFront(A);
   deleteBack(A);
   printf("A's front = %d\n",    front(A));
   printf("A's back = %d\n",    back(A));

   moveTo(A,4);
   insertBefore(A,-1);
   moveTo(A,3);
   insertAfter(A,-2);
   moveTo(A,2);
   delete(A);
   printList(stdout,A);
   printf("\n");
   // printf("%d\n", length(A));

   clear(A);
   printf("%d\n", length(A));

   printf("entering A \n");
   freeList(&A);

   //clear(B);

   printf("A free, entering B \n");
   freeList(&B);

   //clear(C);

   printf("A/B free, entering C \n");
   freeList(&C);

   fclose(out);

   return(0);
}	 
Esempio n. 16
0
nsresult txList::add(void* objPtr) { return insertBefore(objPtr, 0); }  //-- add
Esempio n. 17
0
void editfile (list_ref list) {
    char stdinline[1024];
    int stdincount = 0;
    for(;; ++stdincount) {
        printf ("%s: ", Exec_Name);
        char *linepos = fgets (stdinline, sizeof stdinline, stdin);
        if(isspace(stdinline[0]) != 0) {
            continue;
        }
        if (linepos == NULL) break;
        if (want_echo) printf ("%s", stdinline);
        linepos = strchr (stdinline, '\n');
        if (linepos == NULL || stdinline[0] == '\0') {
            badline (stdincount, stdinline);
        } else {
            *linepos = '\0';
            switch (stdinline[0]) {
            case '$':
                setmove_list (list, MOVE_LAST);
                break;
            case '*':
                print_list(list);
                break;
            case '.':
                printf("%6d: %s\n",counter(list, curr),
                       viewcurr_list (list));
                break;
            case '0':
                setmove_list (list, MOVE_HEAD);
                break;
            case '<':
                setmove_list (list, MOVE_PREV);
                break;
            case '>':
                setmove_list (list, MOVE_NEXT);
                break;
            case '@':
                debugdump_list (list);
                break;
            case 'a':
                insertAfter(list, stdinline+1, curr);
                break;
            case 'd':
                delete_list (list);
                break;
            case 'i':
                insertBefore(list, stdinline+1);
                break;
            case 'r':
                putfilelist (list, stdinline+1, 0);
                break;
            case 'w':
                putfilelist (list, stdinline+1, 2);
                break;
            case '#':
                break;
            default :
                badline (stdincount, stdinline);
            }
        }
    }
    printf (" ^D\n");
}
Esempio n. 18
0
/*Main------------------------------------------------------------------------*/
int main(int argc, char* argv[]) {
   
    //input validation
   if(argc < 3 || argc > 3) {
       
      //usage message
      printf("Usage: %s [input file] [output_file]\n", argv[0]);
      exit(EXIT_FAILURE);
   }
   
   //the number of lines in the file
   int lineCount = 0;
   char line[MAX_SIZE];
   
   //set the String words
   char words[lineCount][MAX_SIZE];

   //open files for input read and output write
   FILE *in = fopen(argv[1], "r");
   FILE *out = fopen(argv[2], "w");

   //checking input write file pointer
   if(in == NULL ) {
      printf("Unable to open file %s for reading\n", argv[1]);
      exit(EXIT_FAILURE);
   }
   
   //checking output write file pointer
   if(out == NULL ) {
      printf("Unable to open file %s for writing\n", argv[2]);
      exit(EXIT_FAILURE);
   }

   //this will determine the size the string words
   while (fgets(line, MAX_SIZE, in) != NULL) {
      lineCount++;
   }
   
   //this will allow the file pointer to be at the beginning
   fclose(in);
   in = fopen(argv[1], "r");
 
   //reset lineCount to walk through the words and copy the pointers
   lineCount = 0;
   
   //copy pointers to string words
   while(fgets(line, MAX_SIZE, in) != NULL) {
      int iter;
      for (iter = 0; iter < strlen(line); iter++) {
         
         //chop the newline
         if (line[iter] == '\n') {
            words[lineCount][iter] = '\0';
            break;
         }
         words[lineCount][iter] = line[iter];
      }
      lineCount++;
   }

   //Declare a list object and initialize it with a 0
   List list = newList();
   append(list,0);

   //InsertSort walk through each item and place in correct spot
   int iter;
   for (iter = 1; iter < lineCount; iter++) {
      
      //words that are at the front and back of the list
      char *curr_word = words[iter];
      char *front_word = words[front(list)];
      char *back_word = words[back(list)];

      // if the word should be at the front of the list
      if (strcmp(curr_word, front_word) < 0) {
         prepend(list,iter);
      }
      
      //if the word should be at the end of the list
      else if (strcmp(curr_word, back_word) > 0) {
         append(list,iter);
      }
      
      //if the word belongs within the list
      else {
          
         //start the beginning of the list and work each word lexicographically
         moveTo(list,0);
         
         //compare each word until you find the correct spot and stop the loop
         while (strcmp(curr_word, words[getElement(list)]) > 0) {
            moveNext(list);
         }
         
         //when stopped this is the correct index so insert here
         insertBefore(list, iter);
      }
   }

   //output the words to the file
   for (moveTo(list,0); getIndex(list)>= 0; moveNext(list)) {
      fprintf(out,"%s\n", words[getElement(list)]);
   }

   //free all nodes in the list
   freeList(&list);
   
   //close the input read and output write files
   fclose(in);
   fclose(out);

   return(EXIT_SUCCESS);
}
void main(){
	int input;  // 사용자 입력 코드
	Dlist D = createDlist(); // 사용자 입력으로 아이템이 입력되는 리스트
    
	Dlist D2 = createDlist();   // join용 리스트
	insertHead(D2,10);
	insertHead(D2,13);
	insertHead(D2,17);
	insertHead(D2,19);
	insertHead(D2,21);
	insertHead(D2,26);

	Dlist newList = createDlist();
	printf("==============140529 201100646 김영태 과제==============\n\n");
	printf("주의!! : movebefore시 기준 노드의 유일성을 보장하기 위하여 중복된 값 입력은 허용되지 않습니다. \n");
	printf("주의!! : Join시 합칠 리스트는 코드상에 미리 정의되어있습니다. \n");
	printf("주의!! : 때문에 Join은 한번밖에 실행되지 않습니다.(그 이상 실행할시 에러)\n\n");
	printf("=====================================================\n\n");

	while(1){
		int val;    // 사용자입력에 따른 변수들
		int node_val;
		dnode d;
		dnode d1;
		dnode d2;
		Dlist splitD;
		Dlist temp;
		char* result = "결과 리스트";

		printf("원하시는 동작에 따라서 숫자를 입력해주세요\n");    // 사용자 인터페이스
		printf("(1: insert Head, 2: insert After, 3: insert before, 4: move before, ");
		printf("5: search, 6: split, 7:join) \n");
		scanf("%d", &input);

		switch(input){
			case 1 :    //  insert Head
				printf("삽입을 원하시는 값을 입력해주세요 : ");
				scanf("%d", &val);
				if(search(D,val)){
					printf("중복된 값입니다\n");
					break;
				}
				insertHead(D,val);
				printList(D,result);
				break;
				
				
			case 2 :  // insert After
				printf("삽입을 원하시는 값을 입력해주세요 : ");
				scanf("%d", &val);
				if(search(D,val)){
					printf("중복된 값입니다\n");
					break;
				}
				printf("어느 값의 노드 다음에 삽입을 원하시는지 말씀해주세요\n");
				d = findNode(D);
				if(d == NULL){
					printf("찾으시는 값이 없습니다\n");
					break;
				}else{
					insertAfter(D,d,val);
					printList(D,result);
					break;
				}
			case 3 :    // insert Before
				printf("삽입을 원하시는 값을 입력해주세요 : ");
				scanf("%d", &val);
				if(search(D,val)){
					printf("중복된 값입니다\n");
					break;
				}
				printf("어느 값의 노드 이전에 삽입을 원하시는지 말씀해주세요\n");
				d = findNode(D);
				if(d == NULL){
					printf("찾으시는 값이 없습니다\n");
					break;
				}else{
					insertBefore(D,d,val);
					printList(D,result);
					break;
				}
			case 4 :    //move Before
				printList(D,"현재 리스트");
				printf("옮길 첫번째 노드를 선택해 주세요 \n");
				d1 = findNode(D);
				if(d1 == NULL){
					printf("찾으시는 값이 없습니다\n");
					break;
				}
				printf("옮길 마지막 노드를 선택해 주세요 \n");
				d2 = findNode(D);
				if(d2 == NULL){
					printf("찾으시는 값이 없습니다\n");
					break;
				}
				printf("어느 노드 전으로 옮기실 건가요?(겹치지 않게 주의해주세요.) \n");
				d = findNode(D);
				if(d == NULL){
					printf("찾으시는 값이 없습니다\n");
					break;
				}
				moveBefore(D,d1,d2,d);
				printList(D,result);
				break;

			case 5 :    // search
				if(findNode(D)){
					printList(D,"현재 리스트");
					printf("찾으신 값이 리스트내에 존재합니다.\n");
					break;
				}else{
					printList(D,"현재 리스트");
					printf("찾으신 값이 리스트내에 존재하지 않습니다.\n");
					break;
				}
			case 6 :    // split
				printList(D,"현재 리스트");
				printf("나눌 기준이 되는 노드의 값을 입력하세요 : ");
				scanf("%d",&val);
				d = search(D,val);
				if(d==NULL){
					printf("찾으시는 값이 없습니다\n");
					break;
				}

				splitD = split(D,d);

				printList(D,"기존리스트");
				printList(splitD,"나눠진 리스트");
				break;

			case 7 :    //join
				printList(D,"현재 리스트");
				while(1){

				}
				printList(D2,"조인할 리스트");
				join(D,D2);
				printList(D,"결과");
				break;
			default :   // default input
				printf("잘못된 입력입니다.\n");
				break;
		}

	}

}
Esempio n. 20
0
void TGroup::insert( TView* p )
{
    insertBefore( p, first() );
}
Esempio n. 21
0
 void addEdge ( Graph G, int u, int v )
 {
 
    // pre-condition
    if ( G == NULL ) 
    {
       printf ( "Graph Error: addEdge() on NULL graph" );
       exit(1);
    }
    // pre-condition
    if ( u < 1 || u > getOrder(G) ) 
    {
       printf ( "Graph Error: u undefined" );
       exit(1);
    }
    // pre-condition
    if ( v < 1 || v > getOrder(G) ) 
    {
       printf ( "Graph Error: v undefined" );
       exit(1);
    }
    // add u to v 
    if(length(G->adjacency[u]) == 0) { 
       append (G->adjacency[u], v );
    }
    
    else 
    {
      moveTo(G->adjacency[u], 0);
      while(getIndex(G->adjacency[u]) != -1 ) 
      {
          if(v < getElement(G->adjacency[u])) {
             insertBefore(G->adjacency[u], v);
             break;
           }
           else {
           moveNext(G->adjacency[u]);
           }
       }
       
        if(getIndex(G->adjacency[u]) == -1) {
          append ( G->adjacency[u], v );
       }
    }
          
       // add v to u 
        if(length(G->adjacency[v]) == 0) { 
       append ( G->adjacency[v], u );
    }
    else 
    {
      moveTo(G->adjacency[v], 0);
      while(getIndex(G->adjacency[v]) != -1 ) {
          if(u < getElement(G->adjacency[v])) {
             insertBefore(G->adjacency[v], u);
             break;
           }
           else {
           moveNext(G->adjacency[v]);
           }
       }
       
       if(getIndex(G->adjacency[v]) == -1) {
          append ( G->adjacency[v], u );
       }
    }
       
    
    G->size++;
    G->size++;
 }
Esempio n. 22
0
int main(void)
{
	element *html = readDocument();

	// createElement
	element *t1 = createElement("t1", "Text node");

	assert("createElement - empty pointers - parentNode", t1->parentNode == NULL);
	assert("createElement - empty pointers - nextSibling", t1->nextSibling == NULL);
	assert("createElement - empty pointers - previousSibling", t1->previousSibling == NULL);
	assert("createElement - empty pointers - firstChild", t1->firstChild == NULL);
	assert("createElement - empty pointers - lastChild", t1->lastChild == NULL);


	// appendChild
	appendChild(html->lastChild, t1);

	assert("Append child test - parent pointer", t1->parentNode == html->lastChild);

	assert("Append only child test - previousSibling pointer", t1->previousSibling == NULL);
	assert("Append only child test - nextSibling pointer", t1->nextSibling == NULL);

	element *t2 = createElement("t2", NULL);
	appendChild(html->lastChild, t2);

	assert("Append second child test - previousSibling pointer to the first child", t2->previousSibling == html->lastChild->firstChild);
	assert("Append second child test - nextSibling pointer to NULL", t2->nextSibling == NULL);

	element *t3 = createElement("t3", NULL);
	appendChild(html->lastChild, t3);

	assert("Append third child test - second child nextSibling pointer equals to the pointer to the last child", t2->nextSibling == html->lastChild->lastChild);

	// replaceChild
	element *r2 = createElement("r2", NULL);
	replaceChild(html->lastChild, r2, html->lastChild->firstChild->nextSibling);

	assert("Replace child in the middle - parent", r2->parentNode == html->lastChild);
	assert("Replace child in the middle - prevSibling", r2->previousSibling == html->lastChild->firstChild);
	assert("Replace child in the middle - nextSibling", r2->nextSibling == html->lastChild->lastChild);

	element *r3 = createElement("r3", NULL);
	replaceChild(html->lastChild, r3, html->lastChild->lastChild);

	assert("Replace last child - prevSibling", (r3->previousSibling == html->lastChild->firstChild->nextSibling) && (r3->previousSibling == r2));
	assert("Replace last child - nextSibling", r3->nextSibling == NULL);

	element *r1 = createElement("r1", NULL);
	replaceChild(html->lastChild, r1, html->lastChild->firstChild);

	assert("Replace first child - prevSibling", r1->previousSibling == NULL);
	assert("Replace first child - nextSibling", r1->nextSibling == r2);

	// removeChild
	removeChild(html->lastChild, r1);
	assert("Remove child - first child removed", html->lastChild->firstChild == r2);

	removeChild(html->lastChild, r3);
	assert("Remove child - last (not least) child is removed", html->lastChild->lastChild == r2);
	assert("Remove child - last (not least) child is removed - siblings check for the remaining child", r2->previousSibling == NULL && r2->nextSibling == NULL);

	removeChild(r2->parentNode, r2);
	assert("Remove child - body is empty", html->lastChild->firstChild == NULL && html->lastChild->lastChild == NULL);

	appendChild(html->lastChild, r1);
	appendChild(html->lastChild, r2);
	appendChild(html->lastChild, r3);

	removeChild(r2->parentNode, r2);
	assert("Remove the middle child - relation between first and last",
			html->lastChild->firstChild->nextSibling == html->lastChild->lastChild &&
			html->lastChild->firstChild == html->lastChild->lastChild->previousSibling);

	removeChild(html->lastChild, r1);
	removeChild(html->lastChild, r3);

	// insertBefore
	appendChild(html->lastChild, r3);

	insertBefore(html->lastChild, r2, r3);
	assert("insertBefore - new firstChild", html->lastChild->firstChild == r2);
	assert("insertBefore - lastChild kept", html->lastChild->lastChild == r3);
	assert("insertBefore - parentNode set", html->lastChild == r2->parentNode);

	insertBefore(html->lastChild, r1, r3);
	assert("insertBefore - siblings", r1->previousSibling == r2 && r1->nextSibling == r3);
	assert("insertBefore - previousSibling->nextSibling == added element", r2->nextSibling == r1);

	removeChild(html->lastChild, r1);
	removeChild(html->lastChild, r2);
	removeChild(html->lastChild, r3);

	// cloneNode
	appendChild(r2, t1);
	appendChild(t1, t2);
	appendChild(r2, t3);

	element *c0 = cloneNode(t2, false);
	insertBefore(r2, c0, t3);

	element *c1 = cloneNode(r2, true);
	element *c2 = cloneNode(r2, false);
	appendChild(html->lastChild, c1);
	appendChild(html->lastChild, c2);

	element *c3 = cloneNode(r3, true); // r3
	insertBefore(html->lastChild, c3, c1);

	// Now it should be in order: r3, r2 deep, r2

	assert("Clone - first r2 is deep", html->lastChild->firstChild->nextSibling->firstChild->firstChild != NULL // html body r2 t1 t2
			&& html->lastChild->firstChild->nextSibling->lastChild != NULL); // html body r2 t3

	deleteElement(r1);
	deleteElement(r2);
	deleteElement(r3);

	deleteElement(html);

	return 0;
}
Esempio n. 23
0
int main(int argc, char* argv[]){

   int count=0;
   FILE *in, *out;
   char line[MAX_LEN];
   char array[MAX_LEN][80];
   char* token = NULL;

   for(int i=0; i<MAX_LEN; i++){
      strcpy(array[i], "");
   }

   List L = newList();
  
  // check command line for correct number of arguments
   if(argc != 3){
      printf("Usage: %s <input file> <output file>\n", argv[0]);
      exit(1);
   }

   // open files for reading and writing
   in = fopen(argv[1], "r");
   out = fopen(argv[2], "w");
   if(in==NULL){
      printf("Unable to open file %s for reading\n", argv[1]);
      exit(1);
   }
   if(out==NULL){
      printf("Unable to open file %s for writing\n", argv[2]);
      exit(1);
   }

   int i = 0;

   // count lines of input file 
   while(fgets(line, MAX_LEN, in) != NULL){
      count++;
      token = strtok(line, " \n");
      while(token!=NULL){
         strcat(array[i], token);
         token = strtok(NULL, " \n");
         i++;
      }  
   }

   // Insertion Sort
   for(int i=0; i<count; i++){
      moveTo(L, 0);
      if(length(L)==0){
         append(L, 0);
      }else{
         while(1){
             if(strcmp(array[getElement(L)], array[i]) > 0){
                insertBefore(L, i);
                break;
             }else{
                moveNext(L);
                if(getIndex(L)==-1){
                   append(L, i);
                   break;
                }
             }
         }
      }
   }

   for(moveTo(L, 0); getIndex(L) != -1; moveNext(L)){
      fprintf(out, "%s\n", array[getElement(L)]);
   }


   // close files
   fclose(in);
   fclose(out);
   freeList(&L);
   return(0);
}
Esempio n. 24
0
DOMNode *DOMParentNode::replaceChild(DOMNode *newChild, DOMNode *oldChild)
{
    insertBefore(newChild, oldChild);
    // changed() already done.
    return removeChild(oldChild);
}
Esempio n. 25
0
void push(ElemType x , Stack * stack){
	insertBefore(x,stack->elem);
	stack->size++;
}